inheritance - State of Derived class object when Base class constructor calls overridden method in Java -
please refer java code below:
class base{ base(){ system.out.println("base constructor"); method(); } void method(){} } class derived extends base{ int var = 2; derived(){ system.out.println("derived constructor"); } @override void method(){ system.out.println("var = "+var); } } class test2{ public static void main(string[] args) { derived b = new derived(); } }
the output seen is:
base constructor var = 0 derived constructor
i think var = 0 occurs because derived object half initialized; similar jon skeet says here
my questions are:
why overridden method called if derived class object isn't created yet?
at point in time var assigned value 0?
are there use cases such behavior desired?
the
derived
object has been created - it's constructor hasn't been run yet. type of object never changes in java after instant created, happens before constructors run.var
assigned default value of 0 part of process of creating object, before constructors run. basically, type reference gets set , rest of memory representing object gets wiped 0 (conceptually, anyway - may have been wiped 0 before, part of garbage collection)this behaviour @ least leads consistency, can pain. in terms of consistency, suppose had read-only subclass of mutable base class. base class may have
ismutable()
property defaulted true - subclass overrode return false. odd object mutable before subclass constructor ran, immutable afterwards. on other hand, it's definitely strange in situations end running code in class before constructor class has run :(
a few guidelines:
try not work in constructor. 1 way of avoiding work in static method, , make final part of static method constructor call sets fields. of course, means won't benefits of polymorphism while you're doing work - doing in constructor call dangerous anyway.
try hard avoid calls non-final methods during constructor - it's cause confusion. document method calls have make very clearly, overriding them knows called before initialization has finished.
if have call method during construction, it's usually not appropriate call afterwards. if that's case, document , attempt indicate in name.
try not overuse inheritance in first place - going become issue when you've got subclass deriving superclass other object :) designing inheritance tricky.
Comments
Post a Comment