Search code examples
javaoopmemory-managementinterfacejvm

Difference between Interface and Class object memory allocation


Suppose there are Interface A and class B, and class B implements the interface;

interface A {
  void hello();
}

class B implements A {
  public int justAField;

  @Override
  public void hello() {
    System.out.println("Hi.");
  }

  public void anotherMethod() {
    System.out.println("Another one.");
  }
}

And let's say, we have these two objects;

A typeInterface = new B();
B typeClass = new B();

My question is, when compiler compiles the code and when the memory allocation begins, we've got two objects right? But one is type A, one is type B, that means 'typeInterface' will have only one method, but 'typeClass' will contain one more field and one more method.

Does these two objects allocate the same amount of memory or 'typeInterface' basically consume much less memory?


Solution

  • No, you have two objects of type B, one stored on a reference of type A, the other one stored on a reference of type B.

    Both objects share the same memory usage size, but you cannot access the methods of B from the reference of type A (the reference named typeInterface), even if the method exists at the referenced object, unless you cast it. If you cast the reference, then the restriction is removed and you can access anotherMethod.

    You must differentiate between references and objects. That's all you need.