Reputation: 19
Here are the codes,I thought the outcome will be "B", cause method "a()" is overwritten, but the outcome is "null", which I don't really understand why. Could someone please explain? thank you so much
public class HelloWorld {
public static void main(String[] args) {
B b = new B();
}
}
class A{
private String name = "A"; // "public" will have the same outcome
public A()
{
a();
}
public void a(){
System.out.println(name);
}
}
class B extends A{
private String name = "B";
public void a()
{
System.out.println(name);
}
}
Upvotes: 0
Views: 234
Reputation: 18245
This code works fine, just remember one GOLDEN RULE: DO NOT CALL OVERRIDEN METHOD FROM CONSTRUCTOR!
When A
initializing it calls A.a()
where a()
is overridden in child class B
, but this class is not initialized yet, therefore all parameters have their default values.
It is much better to split it with two calls;
B b = new B(); // init all classes completely to avoid unobvious states
b.a(); // do what you want
P.S.
Your code works fine, but this is a good or job interview. For real life, it is much better to avoid these situations.
Upvotes: 0
Reputation: 120
I'm not sure but i guess the cause here is when instance variable is initialized.
Constructor of sub-class implicitly call to constructor of super-class. I re-write constructor of class B like this to make thing more clear:
public void B()
{
super();
System.out.println(name);
}
Executing super()
statement, code flow jump to constructor of class A. Executing a()
statement in constructor of class A will jump to method a()
of class B due to polymorphism. At this time variable name
of class B hasn't been initialized yet so it print null (default value of String variable).
After finishing super()
statement, now variable name
is initialized. As far as i know, instance variable will be assigned value after call to super()
. Then in next println
statement it print the string we assigned to name
.
Your source code has no println
statement so it only print null
.
Upvotes: 1
Reputation: 81
You didn't call the overridden method here. That's why it doesn't print 'B'. You will get 'null' as the answer because both name objects were hidden at that time because of you have created an object with the same identifier for both classes.
Upvotes: 0
Reputation: 1815
Because you did not call the method a() in your main function.
Just add b.a() after intialization of class B. And you will get your result.
Thanks Happy coding ;)
Upvotes: 2