子类是否从超类继承私有实例变量 [英] Do Subclasses Inherit Private Instance Variables From Superclasses

查看:132
本文介绍了子类是否从超类继承私有实例变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

子类是否继承私有字段?

这个问题解决了同样的问题,但我不太明白如何满足以下(看似)矛盾的情况。

This question addresses the same problem but I don't quite understand how that satisfies the (seemingly) contradictory situations below.

http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html

说子类不会继承其父类的私有成员。

Says that "A subclass does not inherit the private members of its parent class."

这意味着它既没有继承私有实例变量也没有私有方法?

This means that it neither inherits private instance variables nor private methods right?

但是,如果从父级继承公共访问器方法,它是如何工作的?它返回一个它不知道存在的实例变量?

However, how does this work if it inherits a public accessor method from its parent? It returns an instance variable that it doesn't know exists?

另外,我的计算机科学书籍(Baron的AP计算机科学A)对一个问题有正确的答案(子类)从(超类)继承所有私有实例变量和公共访问器方法。

Also, my computer science book (Baron's AP Computer Science A) has the correct answer to a question that says that "The (Subclass) inherits all the private instance variables and public accessor methods from the (Superclass)."

这不是收缩到oracle的教程吗?

Isn't this in contraction to oracle's tutorial?

感谢您的帮助

推荐答案

私人成员也是继承的。要测试这个,你可以在超类中执行以下操作:

Private members are inherited too. To test this, you can do the following in the superclass:

//...
private String myText = "I'm in the superclass";

private void setMyText(String myTextValue)
{
    this.myText = myTextValue;
}

public void setMyTextPublic(String myTextValue)
{
    setMyText(myTextValue);
}

public String getMyText()
{
    return myText;
}
//...

在继承的类中创建方法:

Create a method in the inherited class:

//...
public void setMyTextInTheSuperClass(String myTextValue)
{
    System.out.println(getMyText());
    setMyTextPublic(myTextValue);
    System.out.println(getMyText());
}

public void setConstantValueToMyText()
{
    setMyTextInTheSuperClass("I am in the child class");
}
//...

并在某处调用setConstantValueToMyText。

And call setConstantValueToMyText somewhere.

这篇关于子类是否从超类继承私有实例变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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