Java中的继承规则 [英] Inheritance rules in java

查看:151
本文介绍了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,因此返回了Cx ["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

    A中的String s = "One"中删除了
  • static,或者
  • 方法public String getS()已从类BC中删除,或者
  • 以上两者
  • 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

也请阅读 @Mike Nakis的答案.

关于代码的最后一句话:import语句可以删除.

One final remark on the code: the import-statements can be removed.

这篇关于Java中的继承规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆