【问题标题】:Java package-only variables and inheritanceJava 仅包变量和继承
【发布时间】:2016-01-09 01:00:40
【问题描述】:

我在不同的包中有这两个类(名为 a 和 b)

package a;
import b.*;

public class Tree 
{
    int health = 100;

    public void show()
    {
        System.out.println(this.health);
    }

    public static void main(String[] args)
    {
        Arb c = new Arb();
        //System.out.println(c.health); is not visible
        c.show();
    }
}

package b;
import a.*;
public class Arb extends Tree
{

}

我知道字段 health 不能被 Arb 类型的实例访问,因为它不可见,因此对于 Arb 的实例不存在。它继承的只是 public void show() 方法。好的,直到现在。 但根据我的测试,通过对象 c 调用方法 show 输出答案 100,作为 a 的初始值对象。

我理解这个的问题是:方法调用 this.health ,所以只要对象 c 调用这个方法,this = c。但是 health 不应该是可见的......

有人可以解释那里实际发生了什么吗?谢谢!

【问题讨论】:

  • 一切都是继承的,而不仅仅是show()(和main);在Arb 中只能访问可见public

标签: java inheritance packages


【解决方案1】:

你的陈述“所以它不存在”是不正确的。它存在,只是不可见。

Arb 的实例也是Tree 的实例,Tree 中的代码可以看到该字段,而Arb 中的代码看不到它。

【讨论】:

    【解决方案2】:

    正如您所说的,Arb 类继承了 Tree 类的公共 show() 方法。当调用 Arb 类的 show() 方法时,实际上是在调用 Tree 中的 show() 方法。因为这个方法可以看到health这个字段,它也可以打印它的值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-09-08
      • 1970-01-01
      • 2015-09-14
      • 1970-01-01
      • 1970-01-01
      • 2015-12-09
      • 1970-01-01
      相关资源
      最近更新 更多