Search code examples
helperutility

How to define a helper method shared by multiple classes?


what would be the best way to go about this? For instance, consider the following code:

public class ObjectA {
    public int data;

    public ObjectA() {
        this.data = 1;
    }

    public changeData(int x) {
        this.data = x;
    }
}

public class ObjectB {
    public int data;

    public ObjectB() {
        this.data = 1;
    }

    public changeData(int x) {
        this.data = x;
    }
}

How can this be refactored so changeData can have both classes can use it? Also, so that changeData will be safe to use.


Solution

  • You could create your helper function and data as part of a base class and derive all other classes from it.