Java中的继承规则 [英] Inheritance rules in java
问题描述
我对Java基础有疑问.我在每个课程中都有 s 属性.当我使用访问器(getS())时,由类的实例获得的 s 的值是不同的.这种情况有规定吗?
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?
主要输出是:
x.s = One
x.getS() = Three
类定义:
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());
}
}
推荐答案
对字段(x.s
)的访问是通过x
的编译时类型(为A
,因此是A
)解决的.的x
[返回"One"]
).
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).
通过getter(x.getS()
)的访问是通过x
的运行时类型解析的(它是C
,因此返回了C
的x
["Three"
]).
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).
其他一些例子:
-
((B) x).s
将返回"Two"
-
((C) x).s
将返回"Three"
-
((A) x).getS()
将返回"Three"
-
((B) x).getS()
将返回"Three"
((B) x).s
will return"Two"
((C) x).s
will return"Three"
((A) x).getS()
will return"Three"
((B) x).getS()
will return"Three"
(我将为什么留给读者练习)
顺便说一句:结果在以下时间不会改变
As an aside: the result does not change when
-
从
-
static
,或者 - 方法
public String getS()
已从类B
和C
中删除,或者 - 以上两者
A
中的String s = "One"
中删除了static
is removed fromString s = "One"
inA
, or- method
public String getS()
is removed from classesB
andC
, or - both of the above
也请阅读 @Mike Nakis的答案.
关于代码的最后一句话:import
语句可以删除.
One final remark on the code: the import
-statements can be removed.
这篇关于Java中的继承规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!