Instead of declaring name
as a field on ClassB
assign someEnum
in the constructor of ClassB
so it uses the field from the supertype. The supertype does not have access to the name
field on the subtype, which causes the NPE when toString
is called.
public ClassB(int some_int) {
super(some_const, some_int);
this.name = SomeEnum.ENUM_1;
}
Full Example
ClassB
public class ClassB extends ClassA {
private static final int some_const = 1;
public ClassB(int some_int) {
super(some_const, some_int);
this.name = SomeEnum.ENUM_1;
}
public static void main(String[] args) {
ClassB b = new ClassB(4);
b.toString();
}
}
ClassA
public abstract class ClassA {
protected SomeEnum name;
protected int some_int;
public ClassA(int someConst, int some_int2) {
}
@Override
public String toString() {
return name.toString().toLowerCase() + " > "
+ Integer.toString(some_int);
}
}