【问题标题】:Java inheritance: hiding fields [duplicate]Java继承:隐藏字段
【发布时间】:2014-03-29 20:49:15
【问题描述】:

我有一个泛型类,它声明了一些字段和一个与它们一起使用的构造函数:

public abstract class GenericClass extends JFrame
{
    protected static String FIELD_1;
    protected static String FIELD_2;
    protected static String FIELD_3;

    public GenericClass()
    {
        super(FIELD_1+" "+FIELD_2+FIELD_3);
    }
}

以及应该隐藏字段并使用超类构造函数的子类:

public class ChildClass1
{
    protected static String FIELD_1 = "hello";
    protected static String FIELD_2 = "world";
    protected static String FIELD_3 = "!";

    public ChildClass
    {
        super();
    }
}
public class ChildClass2
{
    protected static String FIELD_1 = "another";
    protected static String FIELD_2 = "class";
    protected static String FIELD_3 = "!";

    public ChildClass
    {
        super();
    }
}

我不明白为什么创建的 JFrame 的标题为 null nullnull。我做错了什么?

更新

这些类的使用非常简单:

public class Main
{

    public static void main(final String[] args)
    {
        new ChildClass1();
        new ChildClass2();
    }
}

【问题讨论】:

  • 您列出了三个类,但没有使用它们的代码。您如何使用这些课程?
  • @Rajit 虽然这与我的问题无关,但请参阅更新
  • 不可能覆盖超类的实例或类变量。您需要通过 setter 或构造函数设置这些字段。但是你可能会重新考虑使用静态。
  • GenericClass 中的字段完全独立于子类中名称相似的字段。例如,ChildClass.FIELD_1 是“你好”,GenericClass.FIELD_1 是 null。即使在ChildClass 内部,GenericClass.FIELD_1 仍然为空。它与ChildClass.FIELD_1 无关,除了FIELD_1ChildClass 中使用时没有类名,最终引用ChildClass.FIELD_1;仅仅因为这是该语言为您提供的便利。您在标题中提到了“隐藏字段”,所以您似乎已经知道它是如何工作的?

标签: java inheritance abstract-class


【解决方案1】:

因为GenericClassFIELD_1FIELD_2FIELD_3 具有null

public abstract class GenericClass extends JFrame
{
    protected static String FIELD_1;
    protected static String FIELD_2;
    protected static String FIELD_3;

    public GenericClass()
    {   // null +" " +null+null = `null nullnull`
        super(FIELD_1+" "+FIELD_2+FIELD_3);
    }
}

这就是想法:GenericClass 应该只是 DECLARE 字段,子类应该初始化它们。 – Danylo Esterman 41 秒前

字段不能这样,你需要重载抽象类的构造函数并强制子类在构造函数期间传递参数(通过隐藏默认构造函数),然后将这些传递的参数用于JFrame的构造函数

【讨论】:

  • 这个想法是:GenericClass 应该只声明字段,子类应该使用特定于类的值来初始化它们。
猜你喜欢
  • 2012-08-28
  • 2015-07-15
  • 1970-01-01
  • 2015-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-13
  • 1970-01-01
相关资源
最近更新 更多