0

When a class in Java inherits another, does the inherited class become (physically) part of the inheriting class such that its byte-code is added to the .class file for the inheriting class? Or does the .class file for the inheriting class contain only the part specific to it and it's at run time that object details from the two .class files of both classes are built together into one object? If either or both classes was generic, would it have effect on the process? Thx.

Learnerer
  • 483
  • 1
  • 5
  • 12
  • Be aware that generic types are purely hints for the compiler. Below the surface all generic parameter types are effectively just type `Object` with casting. So the bytecode will not see any of the generic parameter types. – Bobulous Nov 17 '17 at 15:54
  • Hi. I read that about generics, but I had this speculation in my mind regarding what exactly happens with inheritance of generic classes. The question was whether that would still be the case when we extend a parameterized generic class - will it still be actually Object under the hood, or will it be the specified type? It sounded intuitive then that this is influenced by how the extended class is incorporated into the new one - if it becomes part of its byte-code then it probably changes into the specified type.. – Learnerer Nov 17 '17 at 17:08
  • I noticed that your question is still "open" - as you didn't accept an answer. Please have a look and decide if you want to [accept](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) an answer. Or let me know if there is something I can do to enhance my input to make it accept worthy. Accepting helps future readers to determine if the problem is solved, and shows appreciation for the people who took the time answering you. Thanks! – GhostCat Aug 30 '18 at 18:50

2 Answers2

2

When A extends B, then only that information is written into the class file for A.

There is no copying of code of any form from B.class to A.class. Meaning: when you change B, there is normally no need to recompile A.

And generics are mainly a compile time feature - any generic type turns into Object in bytecode (that is called type erasure). The class file contains a bit of meta information about which entities were declared as generic type, but thats all. In other words: Java generics are not the same thing as C++ templates.

GhostCat
  • 127,190
  • 21
  • 146
  • 218
0

The second one, for example if you compile the following two classes:

public class Parent {
  public void myMethod(String arg) {
  }
}

public class Child extends Parent {
  public void myMethod(String arg) {
    super.myMethod(arg);
  }
}

Then, after you had compiled both classes, you change the Parent class like:

public class Parent {
  public void myMethod(Integer arg) {
  }
}

You'll get a NoSuchMethodError, this happens because Child call the parent's myMethod at runtime.

I hope it was clear, bye.

Alessandro
  • 4,032
  • 4
  • 26
  • 59