• 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
  • Tim Cooke
  • paul wheaton
  • Liutauras Vilda
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Devaka Cooray
  • Paul Clapham
Saloon Keepers:
  • Scott Selikoff
  • Tim Holloway
  • Piet Souris
  • Mikalai Zaikin
  • Frits Walraven
Bartenders:
  • Stephan van Hulst
  • Carey Brown

Polymorphism, Constructors and Methods

 
Ranch Hand
Posts: 125
2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Dear All,

The source of this question comes from the Online Udemy Course "Pass the Oracle Certified Associate(OCA): Java SE 8 Programmer I EXAM"
Instructor: Udayan Khattry


Please could someone kindly explain how on earth this program prints -1 when executed?



Thanks in advance for any help that you can give.

 
Bartender
Posts: 15737
368
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
  • The main method calls the Derived1 constructor.
  • The Derived1 constructor calls the Base1 constructor.
  • Base1 initializes its own id field to 1000.
  • The Base1 constructor calls the Base1() method that's overridden in Derived1.
  • The Base1() method in Derived1 prints --id. id hasn't been initialized yet, so it prints -1.
  • The Base1() method returns to the Base1 constructor.
  • The Base1 constructor returns to the Derived1 constructor.
  • Derived1 initializes its own id field (which was -1) to 2000.
  • The Derived1 constructor returns to the main method.
  • The main method finishes running.

  • In short, the solution the problem is to realize that the Base1 constructor runs before the Derived1.id field is initialized. Superclass constructors always run before fields in subclasses are initialized.

    The lesson is that you must never call overridable methods from constructors.
     
    There is no greater crime than stealing somebody's best friend. I miss you tiny ad:
    We need your help - Coderanch server fundraiser
    https://coderanch.com/wiki/782867/Coderanch-server-fundraiser
    reply
      Bookmark Topic Watch Topic
    • New Topic