I got this task and I can't quite figure out how to solve it: "Change all three of the x-variables related to the C-class."
class A {
public int x;
}
class B extends A {
public int x;
}
class C extends B {
public int x;
public void test() {
//There are two ways to put x in C from the method test():
x = 10;
this.x = 20;
//There are to ways to put x in B from the method test():
---- //Let's call this Bx1 for good measure.
---- //Bx2
//There is one way to put x in A from the method test();
---- //Ax1
}
}
To test, I set up this:
public class test {
public static void main(String[] args)
{
C c1=new C();
c1.test();
System.out.println(c1.x);
B b1=new B();
System.out.println(b1.x);
A a1=new A();
System.out.println(a1.x);
}
}
Which gives 20, 0, 0.
Now, I figured out I could write Bx1
like this:
super.x=10;
That would change the x
in B
, but I could not figure out how to call it in my test.java
.
How do you get Bx1
, Bx2
, Ax1
, and how do you call them for a test?
You can access the superclass's version of x
by using a superclass type reference:
System.out.println("A's x is " + ((A)this).x);
That will get A#x
.
But in general, it's a very bad idea to shadow a superclass's public instance members.
Example: (live copy on IDEOne)
class Example
{
public static void main (String[] args) throws java.lang.Exception
{
new C().test();
}
}
class A {
public int x = 1;
}
class B extends A {
public int x = 2;
}
class C extends B {
public int x = 3;
public void test() {
//There are two ways to put x in C from the method test():
System.out.println("(Before) A.x = " + ((A)this).x);
System.out.println("(Before) B.x = " + ((B)this).x);
System.out.println("(Before) C.x = " + this.x);
((A)this).x = 4;
System.out.println("(After) A.x = " + ((A)this).x);
System.out.println("(After) B.x = " + ((B)this).x);
System.out.println("(After) C.x = " + this.x);
}
}
Output:
(Before) A.x = 1 (Before) B.x = 2 (Before) C.x = 3 (After) A.x = 4 (After) B.x = 2 (After) C.x = 3