Java Inheritance – Is Code from Superclass Copied or Referred to by Subclass?

inheritancejavaobject-oriented

Class Sub is a subclass of class Sup. What does that mean practically? Or in other words, what is the practical meaning of "inheritance"?

Option 1: The code from Sup is virtually copied to Sub. (as in 'copy-paste', but without the copied code visually seen in the subclass).

Example: methodA() is a method originally in Sup. Sub extends Sup, so methodA() is (virtually) copy-pasted to Sub. Now Sub has a method named methodA(). It is identical to Sup's methodA() in every line of code, but entirely belongs to Sub – and doesn't depend on Sup or is related to Sup in any way.

Option 2: The code from Sup isn't actually copied to Sub. It's still only in the superclass. But that code can be accessed through the subclass and can be used by the subclass.

Example: methodA() is a method in Sup. Sub extends Sup, so now methodA() can be accessed through Sub like so: subInstance.methodA(). But that will actually invoke methodA() in the superclass. Which means that methodA() will operate in the context of the superclass, even if it was called by the subclass.

Question: Which of the two options is really how things work? If none of them is, than please describe how these things actually work.

Best Answer

Option 2.

The bytecode is referenced dynamically at runtime: this is why, for example, LinkageErrors occur.

For example, assume you compile two classes:

public class Parent {
  public void doSomething(String x) { ... }
}

public class Child extends Parent {
  @Override
  public void doSomething(String x) {
    super.doSomething(x);
    ...
  }
}

Now modify and recompile the parent class without modifying or recompiling the child class:

public class Parent {
  public void doSomething(Collection<?> x) { ... }
}

Finally, run a program that uses the child class. You will receive a NoSuchMethodError:

Thrown if an application tries to call a specified method of a class (either static or instance), and that class no longer has a definition of that method.

Normally, this error is caught by the compiler; this error can only occur at run time if the definition of a class has incompatibly changed.