here concept of constructor chaining comes in to picture. In main() we are constructing an object of Mobile class. "Mobile n=new Mobile();"
This will invoke the default constructor of Mobile class. Due to constructor chaining super class(Phone) default constructor will be called. It is the object which decides which method to be called. Here object is of Mobile class so showDevice() of Mobile will be called. It will print "Mobile.showDevice, null".
Then Mobile() will be called and it's showDevice() will be called which will print "Mobile.showDevice,Mobile.device". We created an object n of Mobile class which invokes method showDevice() so it will be executed and print "Mobile.showDevice,Mobile.device".
If in case you declare String device as static :
public class Mobile extends Phone {
static String device = "Mobile.device";
void showDevice() {
System.out.print("Mobile.showDevice,"+device+" ");
}
Mobile() {
showDevice();
}
public static void main(String[] args) {
Mobile n = new Mobile();
n.showDevice();
}
}
The output will be as follows
Mobile.showDevice,Mobile.device Mobile.showDevice, Mobile.device Mobile.showDevice, Mobile.device