Suppose you have the following code
class A {
int i = 4;
A() {
print();
}
void print () {
System.out.println("A");
}
}
class B extends A {
int i = 2; //"this line"
public static void main(String[] args){
A a = new B();
a.print();
}
void print () {
System.out.println(i);
}
}
this will print 0 2
Now, if you remove line labeled "this line"
the code will print 4 4
- I understand that if there was no int i=2; line,
A a = new B();
will call class A, initializes i as 4, call constructor,
which gives control over to print()
method in class B
, and finally prints 4.
a.print()
will call print()
method in class B because the methods will bind at runtime, which will also use the value defined at class A, 4.
(Of course if there is any mistake in my reasoning, let me know)
- However, what i don't understand is if there is int i=2.
why is it that if you insert the code, the first part (creating object) will all of sudden print 0 instead of 4? Why does it not initialize the variable as i=4, but instead assigns default value?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…