2016-11-22 36 views
0

我正在编写演示继承使用的程序,并且我使用super()关键字创建了一个变量。我现在试图将该变量的值放入一个调用它的新方法中,以便我可以在我的main方法中调用该方法以在其他类中使用它的值。如何返回超级变量的值?

下面是相关代码:

食品类(超类)

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; 
    } 
} 

肉类(super关键字子类)

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

主类

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()); 
    } 
} 

任何帮助表示赞赏,谢谢。

+5

为什么当继承的实现工作正常时,你会重写'getName'? – user2357112

+2

我知道你的问题是继承的误解http://docs.oracle.com/javase/tutorial/java/concepts/inheritance.html – litelite

回答

1

请勿覆盖Meat类中的public String getName()。 继承允许在Food的所有子类中继承公共和受保护的方法Food,因此在Meat中。

所以Meat这是一个Food的定义有这种行为:

public String getName() { 
     return name; 
    } 

返回存储在父类中的name领域。

覆盖子类中的方法以编写与父方法完全相同的代码是无用的,不应该这样做,因为它具有误导性。一个读代码的人会问:为什么在子类中重写方法,如果它和父类做同样的事情?


编辑

此外,如果你想从一个子类访问超类声明的字段,你应该:

  • 提供超一流的公共的getter如果该字段是私人的。在这里:

    public String getName() { return name; }

  • 直接使用领域在子类中,如果现场有保护剂。

作为一般规则,你应该避免声明实例字段用修饰符公众,因为通过对象的默认属性应该受到保护,你应该提供方法来修改仅在需要的领域。

所以,宣告你的肉类一样,似乎更适合:

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类,想象你想通过getName()返回的字符串中添加额外的信息,你可以忽略它,为什么不使用字段从超类:

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

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

这里覆盖的方法是有用的,因为在子类中的方法的行为不同于它在一个超类。

4

你可以只是做

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

虽然你甚至都不需要覆盖的方法摆在首位,因为你在super类声明的字段public这意味着它可以是从任何地方访问。

1

简单地写:

public String getName() { 
     return name; 
    } 

这是因为一个名为name变量进行搜索时,Java的进行顺序:

  1. 局部变量(无)
  2. 当前类的字段(无)
  3. 超级的领域(找到)
  4. 超级超级的领域DS(等)

但是,你并不需要在首位的子类覆盖getName()。如果你没有定义它,那么它会继承超类的实现,它完全对应你想要的行为。因此,你做了额外的工作,没有收获。

-1

由于食品类具有的getName声明为public方法做

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

其他的答案显示你怎么做你想要什么。

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

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

你也应该避免setter/getter方法,因为它们只是重定向访问。 (除了该类是没有任何逻辑的DTO)。