2014-03-29 161 views
0

我有一个泛型类,它声明某些字段和一个构造函数,可与他们:Java继承:隐藏字段

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

我不明白为什么创建的JFrames有标题null nullnull。我究竟做错了什么?

更新

使用这些类的很简单:

public class Main 
{ 

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

您已经列出了三个类,但没有使用它们的代码。你如何使用这些类? – Rajit

+1

另请参见:[覆盖超类'实例变量](http://stackoverflow.com/questions/427756/overriding-a-super-class-instance-variables) – Rajit

+0

@Rajit虽然这与我的问题无关,请参阅update –

回答

1

因为GenericClassnull值的FIELD_1FIELD_2FIELD_3

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

该W作为想法:GenericClass应该只是DECLARE字段和子类应该初始化它们。 - Danylo Esterman 41秒前

你不能有这样的说法对田,你需要重载抽象类的构造函数和力的子类(通过隐藏默认构造函数)来传递构造函数中的参数,然后使用这些传递的参数对于JFrame的构造函数

+0

这是这个想法:'GenericClass'应该只是DECLARE字段,并且子类应该使用特定于类的值来初始化它们。 –

+0