Question

I need to override toString() method for all of the concrete method of my abstract class - exactly the same in all cases. So here is what I want to do (SomeEnum is a separate class which has just an enum declaration):

abstract class

public abstract class ClassA {
    protected SomeEnum name;
    protected int some_int;

// Constructor here

@Override
public String toString() {
    return name.toString().toLowerCase() + " > " + Integer.toString(some_int);
}
}

concrete class (example)

public class ClassB extends ClassA {
    private static final int some_const = 1;
    private SomeEnum name = SomeEnum.ENUM_1;

public ClassB(int some_int) {
    super(some_const, some_int);
}
}

For some reason I cannot do it that way without runtime exceptions and I need to declare abstract method in the abstract class and then provide (exactly the same) implementation of toString() in every of the concrete classes implementations.

What is wrong with this approach?

EDIT: The exception I get is NullPointerException that then points me to ClassA.toString().

Was it helpful?

Solution

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

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top