Win a copy of TDD for a Shopping Website LiveProject this week in the Testing forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Frits Walraven
Bartenders:
  • Piet Souris
  • Himai Minh

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

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 954
4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.


 
Marshal
Posts: 75634
354
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
… and welcome to the Ranch
 
Campbell Ritchie
Marshal
Posts: 75634
354
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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: 75634
354
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Danger, 10,000 volts, very electic .... tiny ad:
Free, earth friendly heat - from the CodeRanch trailboss
https://www.kickstarter.com/projects/paulwheaton/free-heat
reply
    Bookmark Topic Watch Topic
  • New Topic