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.