0
class A
{
    void show()
    {
        System.out.println("show");
    }
}
class B extends A
{
    void disp()
    {
        System.out.println("disp");
    }
}
class Prac2
{
    public static void main(String args[])
    {
        A ob = new B();
        ob.disp();
    }
}


/*this thing shows an error */

now my question is :i thought we can use any object reference which must be above hierchy than the object which we are giving.but then here it shows an error...can some one pl explain object reference in detail because till now i use to think that they are only something like pointers but here they are acting differently

Edited by mike_2000_17: Fixed formatting

2
Contributors
2
Replies
3
Views
8 Years
Discussion Span
Last Post by purijatin
0

The reference variable ob is a ref to type A, which means it can refer to any object of type A or of any sub-type of A.
However, because it is declared as A it can only be used to access members that are defined in A, and there is no disp method in A, so its a compile error.
If you override show in B then you can call ob.show, and the implementation of show from B will be used if ob is actually a reference to a type B, but that's only because show is defined in A.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.