简体   繁体   中英

How does the memory allocation works when a reference of superclass is holding an object of subclass?

I went through all plausible answers relating to this question, but none answered what is the purpose of SuperClass ob = new SubClass()?

class SuperClass
{
    int x = 10;
    public void foo()
    {
        System.out.println("In Superclass: "+x);
    }
}

class SubClass extends SuperClass
{
    int x = 20;
    public void foo()
    {
        System.out.println("In Sub Class: "+x);
    }
}

Class Main
{
    Public static void main (String args[])
    {
        SuperClass ob = new SubClass()
        System.out.println(ob.x); //prints 10
        ob.foo(); // print In Sub Class: 20
    }
}

I want to know:

  1. How the memory allocation works in here
  2. What is the purpose of SuperClass reference in holding the subclass object.

The object layout of the subclass is similar to this:

SubClass {
    meta-data
    SuperClass {
        meta-data
        int x
    }
    int x
}

In particular, notice that there are two separate instances of int x . Data members are not overloaded. Overloading only happens with methods. So SubClass.foo() overloads SuperClass.foo() , but SubClass.x only hides SuperClass.x .

When you print ob.x , you're telling the compiler to print SuperClass.x because the compiler only knows that ob is a SuperClass instance. On the other hand, if you call ob.foo() you're actually calling SubClass.foo() because this method is overridden.

The reason you would assign a subclass instance to a superclass reference variable is similar to why you should assign an object to an interface reference. It's to keep your code clean. If you don't need the specific methods that a subclass provides in addition to those of a superclass, you should make your variable a superclass reference. Then you're free to change the implementation class in just one place. Google "program to an interface, not to an implementation" for more details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM