When we call new SomeClass()
new
operator first creates object of SomeClass
but that object has all its fields set to default values (0, '\0', false, null).
After object is created code of constructor is executed to initialize object properly (set its fields to proper values, and possibly do few other things).
But if class has parent class, constructor first (implicitly or explicitly) calls its super()
constructor to ensure that all inherited fields are properly initialized, before we start using inherited methods which may depend on those fields state.
But methods are polymorphic (as long as they are not private
, static
or final
). This means that when in superclass we call method which was overridden, "newest version" of code will be executed (because polymorphism uses actual type of this
instance - returned by new
keyword - to locate class from which it should start searching for code which should be executed - this is called late or dynamic binding).
So since you called getS()
method in AA
superclass but on BB
instance (because that is what new BB
created), overridden code from BB
class was executed. Problem is that this code uses s
declared in BB
class, but that s
wasn't initialized yet. Lets see how default constructor of BB
which was invoked by new BB()
looks like:
BB(){
super(); //calls AA()
s = "hello2"; // by default `s` holds `null` value
// all initialization is moved to constructors
// after superconstructor call
}
So
- before
s = "hello2";
is executed s
(of BB class) holds null
- but before
s
is initialized to "hello2"
super()
is called (which internally calls getS()
)
- since
getS()
is polymorphic code from BB
class for that method will be executed
- but that code (from
BB
) uses s
of BB which wasn't yet initialized, so it holds null
and that is what you see in console.
Because of that it is considered bad practice (in most cases) to put in constructor methods which can be overridden. We should limit ourselves to calling methods which are not polymorphic, which means either private
static
or final
.