Java继承......困惑 [英] Java Inheritance... Confused

查看:104
本文介绍了Java继承......困惑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个抽象的父类,它有多个子节点。我希望孩子能够拥有一个对于该孩子的每个实例都相同的变量。我不想将一个构造函数传递给孩子来告诉它它的名字,因为当它可以被硬编码时,它看起来很愚蠢。从我读过的内容中做了以下隐藏父实例变量并且不能正常工作。

I have a abstract Parent class that has multiple children. I'd like the child to be able to have a variable that is the same for every instance of that child. I'd prefer not to pass a constructor to the child to tell it it's name because that just seems silly when it can be hardcoded. From what I've read doing the following "hides" the parents instance variable and doesn't work as I want.

public abstract class Parent {
    public String name = "the parent";
    public getName(name);
}
public class Child1 extends Parent {
    public String name = "Jon";
}
public class Child2 extends Parent {
    public String name = "Mary";
}

Child1 c = new Child1();
c.getName(); // want this to return "Jon", but instead returns "the parent".

要清楚,基本上我想要的是像c.getClass()。getName()但是我不希望结果依赖于类名,而是依赖于硬编码值。

To be clear, basically what I want is something like c.getClass().getName() but I don't want to have the result of that dependent on the Class name, but rather on a hardcoded value.

谢谢

推荐答案

取决于你真正想要的是什么,有几个解决方案。一种是让子类为父级提供名称:

Depending on what you're actually trying for, there are a couple of solutions. One is to make the child classes provide the name to the parent:

public abstract class Parent {
    protected Parent(String name) {
        this.name = name;
    }
    public getName() {return name;}
}
public class Child1 extends Parent {
    public Child1() {
        super("Jon");
    }

}
public class Child2 extends Parent {
    public Child2() {
        super("Mary");
    }
}

另一种方法是使用方法继承像Isaac Truett建议

Another is to use method inheritance like Isaac Truett suggests.

这篇关于Java继承......困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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