//Program to demonstrate passing objects as parameters
/*
In java, as we are able to pass primitive type values like int, float, double etc,
we can also pass an entire object as a parameter to an object.
This is done as shown in the following program:
*/
class Box
{
int length;
int width;
int height;
Box(int l,int w,int h)
{
length = l;
width = w;
height = h;
}
boolean chkBox(Box b)
{
if((length == b.length) && (width == b.width) && (height == b.height))
return true;
else
return false;
}
}
/*
In the above code chkBox() method checks whether two objects are having the same dimensions
or not. If they are same, the method returns "true" or if they are different, it returns
"false". That is why I have declared the return type as "boolean".
Since I will be passing a Box object as a parameter, I have to receive it with the same type
of variable. That is why I had declared "Box b". Here "b" will be referencing or pointing to
the object passed in the calling function.
*/
class BoxDemo
{
public static void main(String args[])
{
Box b1 = new Box(10,20,30);
Box b2 = new Box(10,20,30);
System.out.println("b1 and b2 are same: "+b1.chkBox(b2)); //Object b2 is passed as a parameter here.
Box b3 = new Box(20,40,60);
System.out.println("b1 and b3 are same: "+b1.chkBox(b3)); //Object b3 is passed as a parameter here.
}
}
Download the program only: http://paste2.org/followup/1832516
/*
In java, as we are able to pass primitive type values like int, float, double etc,
we can also pass an entire object as a parameter to an object.
This is done as shown in the following program:
*/
class Box
{
int length;
int width;
int height;
Box(int l,int w,int h)
{
length = l;
width = w;
height = h;
}
boolean chkBox(Box b)
{
if((length == b.length) && (width == b.width) && (height == b.height))
return true;
else
return false;
}
}
/*
In the above code chkBox() method checks whether two objects are having the same dimensions
or not. If they are same, the method returns "true" or if they are different, it returns
"false". That is why I have declared the return type as "boolean".
Since I will be passing a Box object as a parameter, I have to receive it with the same type
of variable. That is why I had declared "Box b". Here "b" will be referencing or pointing to
the object passed in the calling function.
*/
class BoxDemo
{
public static void main(String args[])
{
Box b1 = new Box(10,20,30);
Box b2 = new Box(10,20,30);
System.out.println("b1 and b2 are same: "+b1.chkBox(b2)); //Object b2 is passed as a parameter here.
Box b3 = new Box(20,40,60);
System.out.println("b1 and b3 are same: "+b1.chkBox(b3)); //Object b3 is passed as a parameter here.
}
}
Download the program only: http://paste2.org/followup/1832516
excellent concept sirji
ReplyDelete