java的继承原则,Java中的继承规则

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值