I am doing this school exercise, and I couldn't figure why the following two cases would have different results.Can someone explain why in the first case int x
of A is 100? Hasn't the int x
in C shadowed int x
in A? I have commented my question in the code as well. Many thanks!
class A { // Case 1
public int x = 1;
public String k() { return "A" + this.x; }
}
class B extends A {
public int x = 10;
}
class C extends B {
public int x = 100;
public String k() { return "C" + this.x; }
}
class TestABC {
public static void main(String[] args) {
A a1 = new C();
C c1 = new C();
}
}
System.out.println(a1.x +"," + c1.x);// It prints out 1, 100.
//However I thought it'd print out 100, 100, as the int x in C shadows int x in A.
Another Case is
class A1 { //case 2
int x=10;
public void method() {
System.out.print("A:" + this.x + " ");
}
}
class B1 extends A1 {
int x=20;
public void method() {
System.out.print("B:" + this.x + " ");
}
public static void main(String args[]) {
A1 s = new B1();
s.method();// It prints out B: 20.
//What's the difference between this one and a1.x in the previous example?
//Why it prints out the subclass but in the previous code a1.x prints out the parent class?
}
}