【发布时间】: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_1在ChildClass中使用时没有类名,最终引用ChildClass.FIELD_1;仅仅因为这是该语言为您提供的便利。您在标题中提到了“隐藏字段”,所以您似乎已经知道它是如何工作的?
标签: java inheritance abstract-class