LooMeenin
LooMeenin

Reputation: 818

Can I use one getter method for several classes?

Is it possible to use the getError() method in the GreenhouseControls class to grab the errorcode of either WindowMalfunction or PowerOut or do I have to include the method in each inner class?

public class GreenhouseControls {

    public int errorcode;

    public class WindowMalfunction extends Event {
        int errorcode = 1; 
    }

    public class PowerOut extends Event { 
        int errorcode = 2;
    }

    getError(){ return errorcode }
}

Upvotes: 0

Views: 72

Answers (1)

Mark Peters
Mark Peters

Reputation: 81104

You can introduce an intermediate superclass to your events that defines the getError method once:

public class ErrorEvent extends Event {
    private final int errorCode;

    protected ErrorEvent(int errorCode) {
        this.errorCode = errorCode;
    }

    public int getError() {
        return errorCode;
    } 
}

public class WindowMalfunction extends ErrorEvent {
    public WindowMalfunction() { super(1); }
}

public class PowerOut extends ErrorEvent { 
    public PowerOut() { super(2); }
}

Upvotes: 2

Related Questions