mxcd
mxcd

Reputation: 2414

NullPointerException because of overwritten function and call by superclass

Following setup:

public class Superclass
{
    private String params;

    public Superclass(String params)
    {
        this.params = params;
        doStuff();
    }

    public void doStuff()
    {
        // uninteresting stuff
    }
}

public class Subclass extends Superclass
{
    private Object someObject;

    public Subclass(String params, Object someObject)
    {
        super(params);
        this.someObject = someObject;
    }

    @Override
    public void doStuff()
    {
        someObject.toString(); // <- causes NullPointerException
    }
}

Superclass creates an User Interface while Subclass should create a more specialized version.

From a software engineering point of view, what would be the cleanest way to prevent the NullPointerException while "Subclass" still extends "Superclass"?

Upvotes: 2

Views: 647

Answers (2)

Makoto
Makoto

Reputation: 106480

The parent class has no apparent reason at construction time to call doStuff.

Simply put, don't put the call there. These classes should be constructed independently of each other. The parent class should not have a dependency on any data from the child to complete its construction; any methods that are overridden by the child that are called in the parent's constructor will introduce this dependency.

If you do find you need to invoke an extra method in the parent, though, you could make a final method and no ill effect would happen, since the child wouldn't have access to that method.

public class Superclass {
    private String params;

    public Superclass(String params) {
        this.params = params;
        doStuffParent();
    }

    public final void doStuffParent() {
        // uninteresting stuff
    }

    public void doStuff() {
        // uninteresting stuff...again?
    }
}

Upvotes: 2

UltraInstinct
UltraInstinct

Reputation: 44454

From a software engineering perspective, you are trying to perform an action on an object that has not yet been constructed. Map this idea to your real class and its job, you'll understand that there's some problem with the super class constructor because its trying to work on an object in a bad state.

That being said, you have a few options.

  • If it makes sense, try to pass Object someObject to the super class. May be the super class really needs it for it to work.
  • Do not call doStuff() within the super class constructor. It probably even makes sense to call it explicitly outside of both constructors.
  • Let your extended class's constructor call doStuff(..).

Upvotes: 0

Related Questions