Issue
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:
- How the memory allocation works in here
- What is the purpose of SuperClass reference in holding the subclass object.
Solution
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.
Answered By - k314159
Answer Checked By - Mildred Charles (JavaFixing Admin)