thestudentnetwork

Sunday, 18 September 2016

Object reference example - Java



In this program we have created: 
  • a class: Box1
  • a parameterised constructor: Box1(int x, int y, int z)
  • two methods: volume() and area() 
  • object: b1 is  a reference variable 
  •  b2 is a  reference variable
  • b2 is initialized with b1 means – “b1 and b2” both are referring same object , thus it does not allocate extra memory.

class Box1{
int w;
int d;
int h;

Box1(int x, int y, int z){
w=x;
d=y;
h=z;
}

double volume(){
return w*d*h;
}

double area(){
return w*d;
}

public static void main(String args[]){
double a,v;

Box1 b1=new Box1(10,20,30);
Box1 b2;
b2=b1;

a=b1.area();
v=b1.volume();
System.out.println("area="+ a);
System.out.println("volume="+v);

a=b2.area();
v=b2.volume();
System.out.println("area="+ a);
System.out.println("volume="+v);


}
}
Share:

0 comments:

Post a Comment

Definition List

Contact

Pages

Support