我对Java基础有疑问。我在每个班级都有s属性。当我使用访问器(getS())时,类的实例获得的s的值不同。这种情况有规定吗?
主要的输出是:
x.s = One
x.getS() = Three
Run Code Online (Sandbox Code Playgroud)
类的定义:
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());
}
}
Run Code Online (Sandbox Code Playgroud)
场(所述的接入x.s)通过的编译时间类型分辨x(其是A,这样A的x[ "One"]返回)。
通过getter(x.getS())的访问通过运行时类型的解析x(即C,因此返回C的x[ "Three"])。
其他一些例子:
((B) x).s 将返回 "Two"((C) x).s 将返回 "Three"((A) x).getS() 将返回 "Three"((B) x).getS() 将返回 "Three"(我将“ 为什么”作为练习留给读者)
顺便说一句:在以下情况下,结果不会改变:
static从取出String s = "One"的Apublic String getS()已从类中删除,B并且C请同时阅读@Mike Nakis的答案。
关于代码的最后一句话:import-statements可以删除。
| 归档时间: |
|
| 查看次数: |
111 次 |
| 最近记录: |