如何return一个超级变量的值?

How to return the value of a super variable?

我正在编写演示继承用法的程序,并且我使用 super() 关键字创建了一个变量。我现在正尝试将该变量的值放入调用它的新方法中,以便我可以在我的主要方法中调用该方法以在其他 classes.

中使用它的值

相关代码如下:

美食class(超级class)

public class Food {

    //field that stores the name of the food
    public String name; 
    //constructor that takes the name of the food as an argument
    public Food(String name){
        this.name = name;
    }
    public String getName() {
        return name;
    }
}

肉class(sub class with super 关键字)

public class Meat extends Food 
{
public Meat() {
    super("Meat");
}
    public String getName() {
        return //get super() value??;
    }
}

主要class

public class Main {

public static void main(String[] args) 
{
     Wolf wolfExample = new Wolf();
     Meat meatExample = new Meat();  
     System.out.println("************Wolf\"************");
     System.out.println("Wolves eat " + meatExample.getName());
    }
 }

感谢任何帮助,谢谢。

你可以这样做

public String getName() {
   return super.getName();
}

尽管您甚至不需要一开始就重写该方法,因为您在 super class 中将字段 name 声明为public 这意味着它可以从任何地方访问。

简单写:

    public String getName() {
        return name;
    }

这是因为在搜索名为 name 的变量时,Java 按以下顺序进行:

  1. 局部变量(none)
  2. 当前 class 的字段 (none)
  3. 超级class的字段(已找到)
  4. 超级超级class的字段(等)

但是,您不需要首先覆盖子class 中的getName()。如果您没有定义它,那么它将继承 superclass 的实现,这与您想要的行为完全一致。因此,您做额外的工作没有任何收获。

不要覆盖 Meat class 中的 public String getName()。 继承允许在 Food 的所有子 class 中继承 public 和 Food 的受保护方法,因此在 Meat.

所以 Meat 这是一个 Food 根据定义具有这种行为:

 public String getName() {
        return name;
    }

其中 returns name 字段存储在父 class 中。

覆盖子class中的方法以编写与父方法中完全相同的代码是无用的,不应这样做,因为它具有误导性。阅读代码的人会疑惑:为什么要覆盖子 class 中的方法,如果它做的事情与父 class 相同?


编辑

此外,如果你想从子class访问在超级class中声明的字段,你应该:

  • 如果该字段是私有的,则在超级 class 中提供一个 public getter。这里:

    public String getName() { return name; }

  • 直接使用subclass中的字段,如果字段有protected修饰符。

作为一般规则,您应该避免使用修饰符 public 声明实例字段,因为默认情况下,对象的属性应该受到保护,您应该提供仅在需要时修改字段的方法。

所以,这样声明你的食物 class 似乎更合适:

public class Food {

    //field that stores the name of the food
    private String name; 
    //constructor that takes the name of the food as an argument
    public Food(String name){
        this.name = name;
    }
    public String getName() {
        return name;
    }
}

在你的 Meat class 中,假设你想在 getName() 返回的字符串中添加额外的信息,你可以覆盖它,为什么不使用来自超级 class :

public class Meat extends Food {
   public Meat() {
     super("Meat");
   }

    @Override
    public String getName() {
      return super.getName + "(but don't abuse it)";
   }
}

这里重写方法很有用,因为子 class 中方法的行为与父 class 中定义的行为不同。

由于 food class 方法 getName 声明为 public do

public String getName() {
    return super.getName();
}

其他答案告诉你如何做你想做的事。

但你不应该这样做(在现实生活项目中)!

面向对象编程中最重要的原则是封装(又名信息隐藏)。这意味着 class 的内部结构不应该对外部可见或不可访问。
因此所有成员变量都应该是私有的。

您还应该避免使用 setter/getter 方法,因为它们只是重定向访问。 (除了 class 是一个没有任何逻辑的 DTO)。