This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Constructors and inheritance  RSS feed

 
Jason Attin
Ranch Hand
Posts: 234
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's my understanding that when creating an object of a class if you don't include any constructor java will insert them for you:


will be always invariably converted into


If you have an inheritance situation like





these will again be converted to these:





So, that's to say that if you don't provide any constructor at all, Java will provide the default constructors and the super constructors, always.
Let's see the scenario in which we do specify a constructor.
This time I provide a constructor:

This mean that java will not provide anymore the default constructor, so when I create my subclass like so


Java will convert the above to this


and that's not good because there is no corresponding empty constructor in the parent class. So I need to amend my subclass to perhaps something like this


and that super(10) will call the parent constructor and we're all happy.
Is there any other scenario to consider with constructors calling parents' constructors?
 
Henry Wong
author
Sheriff
Posts: 23283
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Everything looks fine... nothing wrong with your understanding.

Henry
 
Campbell Ritchie
Marshal
Posts: 55734
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Spot on except that the javac tool doesn't convert the source code, but creates bytecode equivalent to what you wrote, and it is not really correct to call a superclass parent, not even if you see that sort of thing in some books.
You can call other constructors of the same class with this(...); but you cannot use super(); as well because this(...); and super(); must both come first in the constructor.
I don't think there are any other rules about constructors, but you can have a look in the Java® Language Specification (=JLS) and see how much of it you can understand.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!