Pergunta

I've got a generic class, which declares some fields and a constructor which works with them:

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

And child classes which should hide fields and use the superclass constructor:

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

I don't get it why created JFrames have title null nullnull. What am I doing wrong?

update

Using of these classes is quite simple:

public class Main
{

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

Solução

because GenericClass has null values for those FIELD_1, FIELD_2, FIELD_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);
    }
}

This was the idea: GenericClass should just DECLARE fields and subclasses should initialize them. – Danylo Esterman 41 secs ago

You can't have it that way for fields, You need to overload abstract class's constructor and force subclass to pass parameters during constructor (by hiding default constructor) and then use those passed parameter for JFrame's constructor

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top