Monday, July 27, 2009

Why derived class reference can't refere to base class object while reverse is possible?how?

While implementing inheritance in any language (c#,jave,c++), we can refer derived class objects with base class reference variable but reverse is not possible. Why? Is it related with memory? the way your code gets executed?





Logically base class is a subset of derived class, because derived class has all the members of base as well as it can have it's own members. So subset should be able to called by superset and should not be reverse.

Why derived class reference can't refere to base class object while reverse is possible?how?
Let's say you have a base class named Car, and a derived class named Rolls Royce. Now it's easy to see that you can refer to a Rolls Royce as 'a car', but you cannot refer to any car as 'a Rolls Royce'. Well, you could, but you wouldn't be making sense. :-)





Logically, you can do more with a reference to a 'Rolls Royce' than with a reference to a 'Car' because a Rolls Royce is the extended version of the generic 'Car'.





HTH...
Reply:consider example in java


//base class Figure


class Figure{


double dim1,dim2;





//figure constructor


Figure(double a,double b){


dim1=a;


dim2=b;


}


double area(){


System.out.Println("Area is undefined for figure");


}


//subclass of figure





class Rectangle extends Figure{


Rectangle(double len,double breadth){


super(len,breadth);//calls superclass constructor


}


double Area(){


return dim1*dim2;


}


/*************************************...


class DemoFigure{


public static void main(String args[]){


Figure f=new Figure(10,10);


Rectangle r=new Rectangle(9,5);





Figure figref;//create superclass reference variable


//it does not refer to type of object; consider it as reference variable





figref=r;


System.out.println("Area of Rectangle is"+figref.area());





figref=f;


System.out.println("Area of Figure is "+figref.area());


}


}





}





/**********************OUTPUT*********...


Area of Rectangle is 100


Area of Figure is Area is undefined for figure





see the advantage we have used only one method double area() a single robust and re-usable form by method overiding using the concept you stated in your question.





offcourse we can use method overloading concept also but it will not look clear to read as different area will have different parameter.





It does not make sense for derived class object to refer to base class object because all the data and method(functions) are already inherited in derived class object


No comments:

Post a Comment