Register Now

Login

Lost Password

Enter your email to reset your password.

BY Author

Superclass Reference to Subclass Object

It is possible to refer to subclass’ object using its superclass’ reference.
For that we need to assign superclass’ reference with its subclass’ reference or object.

Example

class A 
{
    int i = 10;
}

class B extends A
{
    int j =20;
}

class Demo 
{
    public static void main(String args[])
    {
        A a;
        B b = new B();
        a = b;
        System.out.println("a.i = "+a.i);	
    }
}

Output

a.i = 10

In the above program, we have accessed only superclass’ instance variable i and not subclass’ instance variable j. Because if we tried to access j using superclass’ reference, it would give compile time error.

The reason behind it is that the reference of the superclass cannot access any variable and method of a subclass that is not a member of superclass because it only has knowledge of its own members.

Example

class A 
{
    int i = 10;
}

class B extends A
{
    int j =20;
}

class Demo 
{
    public static void main(String args[])
    {
        A a;
        B b = new B();
        a = b;
        System.out.println("a.j = "+a.j);	
    }
}

We get compile time error,
                                         j cannot be resolved or is not a field

Recently we have said that the reference of the superclass cannot access any variable and method of a subclass that is not a member of the superclass.
But there is an exception to this rule, superclass’ reference can access method of subclass even though it is not a member of the superclass if that method is overridden (soon it will be explained).

 

Leave a reply