Java flow-control -
can explain why code giving output null? when try call new a() instead of new b(), printing current date.
class { date d = new date(); public a() { printdate(); } void printdate() { system.out.println("parent"); system.out.println(d); } } class b extends { date d = new date(); public b() { super(); } @override void printdate() { system.out.println("child"); system.out.println(d); } } public class test { public static void main(string[] args) { new b(); } }
new b() invokes constructor of b, invokes constructor of a. a's constructor calls printdate(), which, due overriding, executes b's printdate(), prints value of d variable of b. however, d variable of b not initialized yet (it initialized after constructor of executed). therefore still null (which default value reference variables).
on other hand, when create instance of a (new a()), printdate of a called, , prints d variable of a, initialized prior constructor of a being executed.
in case it's not clear, b.d not override a.d, hides it. methods can overridden.
Comments
Post a Comment