0% found this document useful (0 votes)
61 views44 pages

Unit - III Object Oriented Programming Concepts

The document discusses object-oriented programming concepts in Java including defining classes, fields, methods, constructors, static members, and method overloading. Key points include: 1) A class defines the state and behavior of objects through fields and methods. Objects are instantiated from classes and use methods to communicate. 2) Constructors initialize objects and can be default, parameterized, or overloaded. They are automatically called when an object is created. 3) Methods operate on fields to define object behavior. Static members like fields and methods belong to the class rather than individual objects. 4) Method overloading allows multiple methods with the same name but different parameters to perform similar tasks using different inputs.

Uploaded by

Keshav Garval
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
61 views44 pages

Unit - III Object Oriented Programming Concepts

The document discusses object-oriented programming concepts in Java including defining classes, fields, methods, constructors, static members, and method overloading. Key points include: 1) A class defines the state and behavior of objects through fields and methods. Objects are instantiated from classes and use methods to communicate. 2) Constructors initialize objects and can be default, parameterized, or overloaded. They are automatically called when an object is created. 3) Methods operate on fields to define object behavior. Static members like fields and methods belong to the class rather than individual objects. 4) Method overloading allows multiple methods with the same name but different parameters to perform similar tasks using different inputs.

Uploaded by

Keshav Garval
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

Unit – III

Object Oriented Programming


Concepts
Topics to be covered…
3.1 Defining classes, fields and methods, creating
objects, accessing rules, this keyword, static
keyword, method overloading, final keyword,
3.2 Constructors: Default constructors, Parameterized
constructors, Copy constructors, Passing object as a
parameter, constructor overloading
class
• Java is true object oriented language.
• Anything in java program must be encapsulated in
class.
• Class defines state and behavior of objects.
• Class create objects and objects use method to
communicate between them.
• Class provide convenient method for packing
together a group of logically related data items
and functions that work on them.
• Class is user defined data type with a template
that serves to define its properties.
• Once class has been defined we can create variables
of that type ,these variables are termed as instance of
classes they are actual objects.
• Everything inside square brackets is optional
Syntax:

class classname[ extends superclass name ]


{
[ variable declaration; ]
[ methods declaration; ]
}
• Any class at least have,
class classname
{
}

• If class does not contain any properties and therefore


can’t do anything.but can compiled and even create
object using it.
• Classname and super classname are any valid java
identifiers.
• Keyword extends indicates ,the properties of super
classname are extended to classname class.
Adding variables to class
• Data encapsulated in a class by placing field inside
body of class, these variables are instance variable.
• Instance variable are created whenever object of class
is instantiated.
Instance variable
class Rectangle Or
Member variable
{
int length;
int width;
}

• Here, variable are only declared and no storage space


has been created in memory.
Adding methods to class
• Class with only data fields (variables) or without
method (that operates on data) has no life.
▫ Objects of that class can not respond to any message.
• Methods declared inside the body of class
immediately after declaration of instance variable.
Type method name ( parameters )
{
Method body; Describe operations to
} be performed on data
Ex:
int sum(a , b , c)
{
// code
}
class Rectangle
{ int length; //variable
int width; //variable
void getData ( int x , int y) //method definition
{
length=x;
width=y;
}
int rectArea ( ) //method definition
{
int area= length * width ;
return (area);
}
}
class A
{ int x;
void method1( )
{
int y;
x=10; // valid
y=x; // valid
}
void method2( )
{
int z;
x=5; // valid
y=1; // invalid
}
}
Creating objects
• How to create object?
• Object is a essential block of memory that contains
space to store all instance variable.
• Creating object is referred as instantiating an object.
• new operator creates objects in java.
it creates object of specified class and returns
reference to that object.

Declaration: classname objectname;


Instantiate: objectname = new classname( );

assigns object reference to the variable


Action Statement result
Declare Rectangle rect ; null rect

Instantiate rect = new Rectangle ( ) ; rect

Reference to rectangle object Rectangle object

Rectangle rect = new Rectangle( );

default constructor
• Class can have any no. of objects of Rectangle.
• Each object has its own instance variables copy so
change to variable of one object have no effect on
variable of another.
Accessing class members
• Syntax:

Objectname . variablename;
Objectname . method name ( parameter list );

Example: rect1 rect2

rect1 . length =15; 15 20


rect1 . Width =10;
10 12
rect2 . Length =20;
rect2 . Width =12;
rect1 . getData( 15 ,10) ;
• Each object that is created must be given initial value.
• We can give by two approach:
1. Uses the (. ) dot operator to access the instance
variable and then assigns values to them
individually.
Ex obj .length=15;
2. Takes the help of a method like getData( ) to
initialize each object individually.
Ex. Obj. getData(15,10);
• It is simple and more concise to initialize an object
when it is first created.
Constructor
• Constructor enables an object to initialize itself
when it is created.
Characteristics :
• Constructor have the same name as the class name
itself.
• Constructor do not specify a return type , not even
void(because they return the instance of the class
itself).
• Constructor can not be inherited , through a derived
class can call the base class constructor
Constructor
• Constructor is a special type of method.
• Mainly two types of constructor
▫ Default constructor
▫ Parameterized constructor
• When you do not explicitly define a constructor for a
class , java creates default constructor.
• Default constructor automatically initialize instance
variable to zero.
• Once you define your own constructor ,the default
constructor is no longer used.
Class Rectangle
Rectangle ( )
{
length=50; width=20;
}
Example
class Rectangle
{
int length, width;
Rectangle( int x , int y) //defining constructor
{
length=x;
width=y;
}
int rectArea( )
{
return ( length * width );
}
class ConstDemo1
{
public static void main( String args[ ])
{
Rectangle rect1=new Rectangle ( 15 ,10 );
// calling constructor
int area1=rect1.rectArea( ) ;

System . out .println( “ Area= “ + area1) ;


}
}
Output :
area1=150
Constructor overloading
• When multiple constructor of same name with
different arguments in a single class is called
Constructor overloading.
Ex class Demo
{
Demo( )
{ ----- }

Demo( int a)
{ ------ }

}
Example
class A
{
A( ) // definition of default constructor
{
System . out . println( “ Constructor demo “ );
}

A( int x) // definition of parameterized


constructor
{
System . out .println (“ value of x=“ + x);
}
}
class ConstructorDemo
{
public static void main( String args[ ])
{
A obj1=new A( ); // calling default constructor
A obj2=new A(5); // calling parameterized
constructor
}
}

Output:
Constructor Demo
Value of x=5
Copy constructor
class A
{
int x;
A(int a)
{
x=a;
}
A(A obj)
{
System.out.println("copy cosnst");
System.out.println("x="+obj.x);
}}
class Copy1
{
public static void main(String args[])
{

A a2=new A(10);
A a3=new A(a2);

//A obj=a2;

}
}
Method overloading
• In java ,it is possible to create methods that have
same name but different definitions . this is called
method overloading.

• Definition : multiple methods of same name with


different arguments in a single class is called Method
overloading.

• It is used when objects are required to perform


similar tasks but using different input parameters.
• When we call up a method in object ,java matches up
method name first then the number and type of
parameters to decide which one of definitions to
execute this process is polymorphism.

• In definition all method should have same name but


different parameter lists ( number of parameter or type
of parameters).
• In java ,we can overload method but not variable or
operator.
• Java uses type and number of argument to call a
method at runtime.
class Demo
{
void display( )
{
System .out .println( “ method overloaded”);
}

void display (int x)


{
System .out .println( “ x=” + x);
}
}
class Overload
{
public static void main(String args[ ] )
{
Demo obj= new Demo( );

obj.display( ); //method without parameter


obj.display(10); //method with parameter
}
}
Static members
• Class has two section
1. Declare instance variable
2. Declare methods
they are accessing using object ( . Dot operator )
• Definition:
Static is a member that is common to all objects and
accessed without using a any object.

Members belongs to class as whole rather than the


objects created from class.
Example:
static int count;
static int max( int x , int y) ;
• Static members are associated with class rather than
individual objects , they are sometimes referred as
class members and class method.
• They are used when we want to have variable
common to all instance of class.
• They can be called without using object ,also
available for use by other classes.
• Methods that are of general utility but do not directly
affect an instance of that class are declared as class
method( static methods).
Math. sqrt( )
Class method / static methods

• Static methods are called using only with classname(


no object have been created).

Limit to use static members:


1. They can only call other static methods.
2. They can only access static data.
3. They can not refer to this or super in any way
class Mathop
{
static float mul ( float x, float y)
{
return x * y;
}

static float divide ( float x, float y)


{
return x / y;
}
}
class StaticDemo
{
public static void main( String args[ ])
{
float a=Mathop .mul (4.0,5.0);
float b=Mathop .divide( a , 2.0);

System .out. println( “ b “ + b );


}
}
Output:
b=10.0
this keyword
• this hides Instance variable.
• It is used in method body to refer to the
members(variables) of current object.
• Current object is a object whose method is being called.
• this keyword used in constructor.
• this is used to make different variable name if one of
argument / parameter has same name as other method.
Circle (int x ,int y, int z )
Circle (int x, int y)
• Method argument can have same name as one of
class’s member variable.
• Typically with an method body you can just refer to
directly to the member variable.
class Circle
{
int x , y ;
public Circle (int x ,int y, int radius )
{
this. x =x;
this. y=y;
this. radius=radius;
}
}
class Circle_this
{
public static void main(String args[])
{
Circle c1=new Circle( 50,50,25);
Circle c2=new Circle( 10,10,5);

System.out. println(c1.x + " " + c1.y +" "+ c1.radius);


System.out. println(c2.x + " " + c2.y +" "+ c2.radius);
}
}
final keyword
• final is a keyword.
• final means can not be changed or it is final.
• It is same as const in c++.
• It is used for efficiency.
• final can be used with
1. Variable (data)
2. Methods
3. classes
1. final variables
• final specifies that the value of variable is final and
must not be changed.
• final variable name must be in capital letters.

• All final variable must have an initial value.(it can’t


specify later).
Ex: final int SIZE=100;
final float PI= 3.14f;
• final variable behaves like class variable.
• They do not take any space on individual object.
2. final method
• All methods and variable can be overridden by default
in subclasses.

• We can prevent overriding of methods of super class by


declared as final.

• If we declare super class’s method as final then it can


not be override by its subclass.
class A
{
final void display( )
{
---------
}
}
class B extends A
{
void display() //invalid
{
--------
}
}
3. final class
• If class is declared with final modifier ,then class can
not be extended and this will ensure that the exact
properties and behavior of class.
• final class cannot be sub classed.
• If we declare class as final ,it prevents any
unwanted extension to the class.
• It allows compiler to perform some optimization when
method of class is invoked.
• Many classes of java .lang are declared as final.
• Methods of non abstract class can be declared as final.
final class A
{
//body

}
class B extends A //invalid ,it gives Error
{

//body

}
Any ?

You might also like