Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java flow-control

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();
    }
}
like image 205
chiranjeevi Avatar asked Nov 19 '14 09:11

chiranjeevi


2 Answers

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.

like image 126
Eran Avatar answered Oct 06 '22 00:10

Eran


Declare Date as Static

static Date d = new Date();
    public B(){
        super();
    }
    @Override
    void printDate(){
        System.out.println("child");
        System.out.println(d);
    }
like image 32
SonalPM Avatar answered Oct 06 '22 01:10

SonalPM