Java inheritance

jdavidb on 2008-01-10T13:53:02

I've been on the new job a month as of today. Most of that time has been spent getting up to speed on Java itself.

Yesterday I was getting some weird errors out of my IDE that didn't make any sense at all. It kept saying it couldn't find a certain constructor I was expecting to be there. I vaguely remembered having a similar error last week with the command-line javac and a couple of classes I was playing with; I'd fixed it by working around it since I wasn't devoted to getting those classes perfect.

But yesterday I wanted to find out what was going on. I started Googling and digging through a Java book. Finally I realized what was happening:

Ladies and gentlemen, after nearly a month of solid Java study, I did not realize until late yesterday afternoon that while Java subclasses inherit methods, they do not inherit constructors.

Papa always said I was oblivious. :)


Really?

Alias on 2008-01-11T00:16:39

I'm not sure I realized that either :/

I did a whole Java project without apparently realizing it.

Re:Really?

jdavidb on 2008-01-11T14:20:28

ROTFL! Now I feel better!

I'm also still struggling with the fact that constructors aren't really methods that just happen to return a new object. In fact they don't return anything at all.

I believe the site I found that clarified the issue of method inheritance vs. constructor inheritance stated that calling constructors methods was a bit like saying the platypus was just another mammal. But then, when I finally tracked down the statement about the lack of constructor inheritance in O'Reilly's Learning Java (and it eluded me because it is not in the section on inheritance; it's in an earlier section), they basically admitted that constructors are methods with some really serious differences.

For the record, constructors and methods are different in the Java reflection API. I wrote a little utility awhile back that basically reads a class file and spits out as much of the original code as it can get from the reflection API, providing a class file full of declarations. (All this was an exercise in the reflection API, but more importantly just in writing a complex Java program.) I was profoundly disturbed by the duplicated code I had to output method and constructor declarations, but I found it was impossible to find a way to reuse the code, as it had to be different for both Method and Constructor arguments.