Thanasis
Thanasis

Reputation: 25

Default variable in static method

I have a method (ex. helpMethod) that appears in many of my project classes and does something with a variable (ex. xVar) present in all of these classes as a private class property. I would like to make this method static in a default class and use it from there. Is it possible to avoid having to pass xVar as an argument to the static implementation?

Something like:

class helpClass {
    static void helpMethod() {
        return ++xVar;
    }
}

class demoClass {
    private int xVar = 0;

    int addToXVar() {
        helpClass.helpMethod();
    }
}

Instead of:

class helpClass {
    static void helpMethod(int xVar) {
        return ++xVar;
    }
}

class demoClass {
    private int xVar = 0;

    int addToXVar() {
        helpClass.helpMethod(xVar);
    }
}

Upvotes: 0

Views: 86

Answers (1)

Peter Lawrey
Peter Lawrey

Reputation: 533442

What you can do to avoid having to pass a reference to the demoClass is use a super class.

class helpClass {
    protected int xVar = 0;

    void helpMethod() {
        ++xVar;
    }
}

class demoClass extends helpClass {

    int addToXVar() {
        helpMethod();
    }
}

Or you can use an interface in Java 8+

interface helper {
    int getXVar();
    void setXVar(int xVar);

    default void helpMethod() {
        setXVar(1 + getXVar());
    }
}

class demoClass implements helpClass {
    private int xVar = 0;

    int addToXVar() {
        helpMethod();
    }

    public int getXVar() { return xVar; }
    public void setXVar(int xVar) { this.xVar = xVar; }
}

Upvotes: 1

Related Questions