The object can be passed to a method as an argument. Using dot operator the object's value can be accessed. The parameter passed to this method is an object.
Objects as Parameters
The
object can be passed to a method as an argument. Using dot operator the
object's value can be accessed. Such a method can be represented syntactically
as -
Data Type name_of_method(object_name)
{
//body of method
}
Following
is a sample Java program in which the method area is defined. The parameter
passed to this method is an object.
Java
Program[ ObjDemo.java]
public
class ObjDemo {
int
height;
int
width;
ObjDemo(int
h,int w)
{
height=h;
width=w;
}
void
area(ObjDemo o)
{
int
result (height+o.height)*(width+o.width);
System.out.println("The
area is "+result);
}
}
class
Demo {
public
static void main(String args[])
{
ObjDemo
obj1 = new ObjDemo (2,3);
ObjDemo
obj2= new ObjDemo(10,20);
obj1.area(obj2);
}
}
Output
F:\test>javac
ObjDemo.java
F:\test>java
Demo
The area
is 276
Program
Explanation
• The
method, area has object obj2 as argument. And there is another object named
obj1 using which the method area is invoked. Inside the method area, the height
and width values of invoking object are added with the height and width values
of the object to be passed.
• When
an object needs to be passed as a parameter to the function then constructor is
built. Hence we have to define constructor in which the values of the object
are used for initialization.
Object Oriented Programming: Unit II: Inheritance, Packages and Interfaces : Tag: : Syntax with Example Java Programs - Objects as Parameters
Object Oriented Programming
CS3391 3rd Semester CSE Dept | 2021 Regulation | 3rd Semester CSE Dept 2021 Regulation