I have a question about the basics of java. I have the s attribute in each class. The value of s gotten by the instance of the class is different when I use the accessor (getS()). Is there a rule for this case?
The output of the main is :
x.s = One
x.getS() = Three
The classes definition :
package com;
import com.Test1.A;
import com.Test1.B;
public class Test1
{
public static class A
{
public static String s = "One";
public int x = 10;
public String getS()
{
return this.s;
}
}
public static class B extends A
{
public final String s = "Two";
public String getS()
{
return this.s;
}
}
public static class C extends B
{
public static int x = 1;
public static String s = "Three";
public String getS()
{
return this.s;
}
}
public static void main(String [] args)
{
A x = new C();
System.out.println("x.s = "+x.s);
System.out.println("x.getS() = "+x.getS());
}
}
解决方案
The access of the field (x.s) is resolved through the compile-time type of x (which is A, so A's x ["One"] is returned).
The access through the getter (x.getS()) is resolved through the runtime type of x (which is C, so C's x ["Three"] is returned).
Some other examples:
((B) x).s will return "Two"
((C) x).s will return "Three"
((A) x).getS() will return "Three"
((B) x).getS() will return "Three"
(I leave the why as an exercise for the reader)
As an aside: the result does not change when
static is removed from String s = "One" in A, or
method public String getS() is removed from classes B and C, or
both of the above
Please read @Mike Nakis' answer as well.
One final remark on the code: the import-statements can be removed.