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:
Now modify and recompile the parent class without modifying or recompiling the child class:
Finally, run a program that uses the child class. You will receive a NoSuchMethodError: