class A { int x = 1; }
class B extends A { }
class C extends B { int x = 2;}
public class classTest {
public static void main(String[] args) {
A w = new A(); System.out.println(w.x);
B u = new B(); System.out.println(u.x);
C v = new C(); System.out.println(v.x);
A [] a = { new A(), new B(), new C()};
for (int i=0; i<3; ++i)
System.out.println(a[i].x);
}
}
So for this, it prints out:
1
1
2
1
1
1
Why does the variable v
that is part of Class C
output a different one when ran each time? For example, in the C v = new C(); System.out.println(v.x);
it outputs 2
and in the last loop in:
for (int i=0; i<3; ++i)
System.out.println(a[i].x);
}
It would print out 1
? Why isn't the first output for running Class C
be 1
since it extends it, so x
would equal to 2
but then would be overwritten by having x equal to 1
from Class B
that is extending Class A
which runs the x = 1
?
I am taking courses in college and we are just barely touching on this topic.
Thank you.