Saturday, March 4, 2017

Reference To Subclass Object (Object Slicing)

Tags

A Superclass reference variable can refer to a Subclass Object .By doing this the superclass reference variable can access only those members of subclass object which are inherited (those are members of superclass).

Following Code will illustrate the concept:

Code::

class Super
{
    int a,b;
    void show()
    {
        System.out.println(a+b);
    }
}
class Sub extends Super
{
    int c;
    void display()
    {
        System.out.println(a+b+c);     // a,b are the members of superclass
    }
}
public class Inheritance
{

    public static void main(String[] nt)
    {
        Super ob;
        Sub ob2=new Sub();
        ob2.a=50;
        ob2.b=10;
        ob2.c=10;
        ob=ob2;         //superclass reference  variable is assigned a subclass object
        ob.show();
        ob2.display();
    }
}
Output::

Converse is not True i.e a Subclass variable cannot refer to a Superclass object.
Reason behind this can be that Subclass has some members which are not in Superclass so here error occurs.