educative.io

Educative

Even when class variable is declared later, how does the method returns null? How does it work?

class Demonstration {

public static void main( String args[] ) {

    (new SpecialPerson()).print();

}

}

class SpecialPerson {

String fullName = init();

String name = "batman";

public SpecialPerson() {

    name = "superMan";

}

private String init() {

    return name;

}

public void print() {

    System.out.println(fullName);

}

}

@Amit_Kumar

Because it is calculated on the compile time and not on the run time. Since an object is created and the print() function is invoked which is printing full name which calling the init function which is returning name, at this point compilation is done(at init() function). As init is again returning a variable, it will print null, if we want to print something than we can return “anything” inside init() function rather than a variable.