简体   繁体   English

Java子类调用超类

[英]Java subclass calling superclass

I'm having a little trouble with inheritance. 我在继承方面遇到了一些麻烦。 What i have done is made a superclass as some of the attributes in the subclasses were identical. 由于子类中的某些属性相同,因此我做了一个超类。

I am trying to reference the superclass, I tried putting super(name); 我正在尝试引用超类,我尝试放置super(name); above the line name = replacementName; name = replacementName;上方name = replacementName; it will not compile saying name has private access in the Superclass 'person'. 它不会编译说name has private access in the Superclass 'person'. I know that it won't access a private field but how can I get the name from the superclass in a subclass method? 我知道它不会访问private字段,但是如何在子类方法中从超类获取名称呢?

Here is the method. 这是方法。

public void changeName(String replacementName){
    name = replacementName;
}

Help appreciated. 帮助表示赞赏。

You have several options : 您有几种选择:

1 - In your super class, use private declaration for the name attribute and add public (or protected) getters/setters. 1-在您的超类中,对name属性使用私有声明,并添加公共(或受保护的)getter / setter方法。 Then you can modify your super class field from your child class using the setter method. 然后,您可以使用setter方法从子类中修改您的超类字段。

2 - In your super class, use protected declaration for your name field. 2-在您的超类中,对名称字段使用受保护的声明。 Then you can access it directly from your child class. 然后,您可以直接从子班级访问它。

... ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM