Btechadda.com

OOPS/JAVA UNIT 3 Super class reference can refer to sub class object

by hkesavaraju on Apr.02, 2010, under Java

Super class reference can refer to sub class object:

observe the following program.

class Box
{
double w,h,d;
Box(Box ob);// object is passed to constructor
{
w=ob.w;
h=ob.h;
d=ob.d;
}
Box( double w1,double h1,double d1)
{
w=w1;
h=h1;
d=d1;
}
Box()
{
w=-1;
h=-1;
d=-1;
}
Box(Double len)
{
w=h=d=len;
}
double volume()
{
return w*h*d;
}
}
class BoxWeight extends Box
{
double m;
BoxWeight(double w1,double h1,double d1,double wg)
{
w=w1;
h=h1;
d=d1;
m=wg;
}
}
class demo
{
public static void main(String args[])
{
BoxWeight m1=new BoxWeight(2,3,4,6.0);
BoxWeight m2=new BoxWeight(10,20,30,8.0);
double vol;
vol=m1.volume();
System.out.println(“volume of object m1 is”+vol));
System.out.println(“weight of object m1 is”+m1.m);
vol=m2.volume();
System.out.println(“volume of object m2 is”+vol);
System.out.println(“weight of object m2 is”+m2.m);
}
}

Output:

 volume of object m1 is: 24.0

weight of object m1 is: 6.0

volume of object m1 is: 48000.0

weight of object m1 is: 8.0

Note: (i) The advantage of inheritance is any number of more specific sub classes are created for a single super class.

(ii) When a super class reference referred to sub class object , it can access only those parts that are defined by super class because it don’t have any knowledge on the members added to it.

The following program illustrates super class reference assigned a sub class object:

Fir the above code, include the following class instead of one that provided above.

class refdemo
{
public static void main(String args[])
{
BoxWeight wb=new BoxWeight(2,3,4,6.0);
Box pb=new Box();
double vol;
vol=wb.volume();
System.out.println(“volume of weightbox is”+vol);
System.out.println(“the weight of weight box is”+wb.m);
pb=wb;   // super class reference pb now referring to sub class object wb, so pb access members that were defined by itself(super class) but not access sub class object members
vol=pb.volume();
System.out.println(“volume of box object is”+vol);
// System.out.println(“weight of box is”+pb.m);         // which raises compiler error.
}
}

Output:

volume of boxweight is: 24.0

weight of weightbox is 6.0

volume of box object is:24.0


Leave a Reply

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Blogroll

A few highly recommended websites...