1
public class Test
{
  public static void main(String args[])
  {
    A a = new B(); // object of type B
  }
}

Here the object is of type Class B but is referred by a variable of type Class A

Doing A a = new A() and A a = new B() both only allow me to access members and methods of Class A then why should I instantiate variable a with constructor of Class B ?

How is this exactly represented in Memory and what exactly happens ?

1 Answers1

-1

Declaring a variable as an ancestor type allows you to switch the implementation on the fly. For example...

public static void main(String[] args) {

    List<String> stringList;

    stringList = new ArrayList<>();

    // Stuff Happens and now I need a LinkedList...

    stringList = new LinkedList<>();
}

If I declared stringList as an ArrayList from the start, I wouldnt be able to switch it to use a LinkedList instead.

As for how it looks in memory. My limited understanding is that the Compiler will care about the Declared Class for TypeSafety but Runtime and Memory will only care about the Instantiated Class.

Steve
  • 981
  • 1
  • 8
  • 22