Win a copy of Practice Tests for OCP Java 17 Certification Exam (1Z0-829) this week in the OCPJP 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:
  • Tim Cooke
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Liutauras Vilda
Sheriffs:
  • Rob Spoor
  • Junilu Lacar
  • paul wheaton
Saloon Keepers:
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Carey Brown
  • Scott Selikoff
Bartenders:
  • Piet Souris
  • Jj Roberts
  • fred rosenberger

Constructor initialization

 
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi all
What i understand from inheritance is that the base class is first initialise b4 the sub.
Why is it that the following code is accessing the overriden method from sub instead of base when calling from base constructor.
To me the subclass is not initialise yet,but still it access that method.
I need some clarity.
Thanks for your help.
class Base
{
void B(){System.out.println("B() method in Base ");}
void A(){System.out.println("A() method in Base ");
B();}
Base(){System.out.println("Base constructor");
A();
}
}
public class Sub extends Base
{
void A(){System.out.println("A() method in Sub ");
B(); }
void B(){System.out.println("B() method in Sub ");}
public static void main(String args[])
{
new Sub();
}
}
 
Ranch Hand
Posts: 1211
Mac IntelliJ IDE
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Think about it this way,
when an object is created, it contains the type-information that indentifies what type(class) it is. So, even thought you are calling that method from the base class constructor, JVM knows what type it REALLY is, and used the late binding to call the subclass method.
Hope that helped. Experiment with making that method static or private, think about why it shows different behaviour then
 
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This is one of those not so pretty Java gotchas.
cornel, I agree that it just seems odd to be able to call a method of an object that would seem to not yet be fully initialized - but you can. For example, this obnoxious program:displays 0 when 2 were perhaps expected.

To be safe, just never call an overridable (that may not be a real word) method from a constructor (make those initializing methods private).
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic