0

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.
Newbie101
  • 3
  • 2
  • What do you mean by "How the memory allocation works in here"? What's the thing you're actually trying to understand? – Andy Turner Aug 05 '22 at 11:46
  • Is the `SuperClass ob = new SubClass()` the line in question? This line is a pretty straightforward application of the [Liskov Substitution Principle](https://en.wikipedia.org/wiki/Liskov_substitution_principle). Note that in memory (and in general), `ob` is _still_ a `SubClass`, and will act like a `SubClass`, but is simply referred to as a `SuperClass`. This is useful in cases where the underlying subclass in use may change, but the overall expected behavior remains the same (think `List` and `ArrayList`/`LinkedList`/etc). Java doesn't [slice](https://en.wikipedia.org/wiki/Object_slicing) – Rogue Aug 05 '22 at 12:07

1 Answers1

0

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.

k314159
  • 5,051
  • 10
  • 32