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();
}
}
After all inputs, I hope following answer satisfies,
As B also has field d, A.d is not inherited to B, where B has its own copy of d.
So when the control is in B.printDate(), it tries to look for A.d (because function is called from A).
this works fine if I remove following line from B