Java中的继承规则

sam*_*ara 2 java inheritance

我对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)

Tur*_*g85 5

场(所述的接入x.s)通过的编译时间类型分辨x(其是A,这样Ax[ "One"]返回)。

通过getter(x.getS())的访问通过运行时类型的解析x(即C,因此返回Cx[ "Three"])。

其他一些例子:

  • ((B) x).s 将返回 "Two"
  • ((C) x).s 将返回 "Three"
  • ((A) x).getS() 将返回 "Three"
  • ((B) x).getS() 将返回 "Three"

(我将“ 为什么”作为练习留给读者)

顺便说一句:在以下情况下,结果不会改变:

  • static从取出String s = "One"A
  • 方法public String getS()已从类中删除,B并且C
  • 以上两个

请同时阅读@Mike Nakis的答案

关于代码的最后一句话:import-statements可以删除。