Can anyone explain why this code is giving output as null? When I try to call new A() instead of new B(), it is printing the current date.
class A
{
Date d = new Date();
public A()
{
printDate();
}
void printDate()
{
System.out.println("parent");
System.out.println(d);
}
}
class B extends A
{
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 the constructor of B, which invokes the constructor of A. A's constructor calls printDate(), which, due to the overriding, executes B's printDate(), which prints the value of d variable of B. However, d variable of B is not initialized yet (it will only be initialized after the constructor of A is executed). Therefore it is still null (which is the default value for reference variables).
On the other hand, when you create an instance of A (new A()), printDate of A is called, and it prints the d variable of A, which was initialized prior to the constructor of A being executed.
In case it's not clear, B.d does not override A.d, it just hides it. Only methods can be overridden.
Declare Date as Static
static Date d = new Date();
public B(){
super();
}
@Override
void printDate(){
System.out.println("child");
System.out.println(d);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With