• Post Reply Bookmark Topic Watch Topic
  • New Topic

OOP, Two constructors are called. One constructor without the proper parameter.  RSS feed

 
Jae An
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm having trouble understanding the sample code from my textbook. The main method calls both constructors. I'm confused why this happens although the constructor in class B does not have an int as a parameter. Thank you for your time.
 
Tushar Goel
Ranch Hand
Posts: 934
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
HI Jae, do you aware of 'super()' ?

In a sub class constructor, compiler runs 'super()' as the first statement. This is implicit call and happens automatically by the compiler. In your case,
class B is super class and class A is sub class. So when you call class A constructor it will call 'super()' implicitly which then calls super class no args constructor.
that's why you see first B class constructor statement executes then A class statement executes.


 
Campbell Ritchie
Marshal
Posts: 56546
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
… and welcome to the Ranch
 
Campbell Ritchie
Marshal
Posts: 56546
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The full details of the object creation process are in the Java® Language Specification (=JLS), I think this section. Beware: the JLS can be difficult to read.
 
Campbell Ritchie
Marshal
Posts: 56546
172
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And when you read the JLS link you will find that three constructors are called when you run your program.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!