创建类的“变体”同时仍保持Java中的类层次结构的简便方法?

时间:2019-02-19 16:54:46

标签: java inheritance dry

说我有这些课程:

interface X {
    public void setX(int x);
    public int getX();
    public void say();
}

interface Y extends X {
    public void shout();
}

class BaseX implements X {
    private int x;
    public BaseX(int x) {setX(x);}

    public void setX(int x) {this.x = x;}
    public int getX() {return x}

    public void say() {
        System.out.println(getX());
    }
}

class BaseY extends BaseX implements Y {
    private int y;
    public BaseY(int x) {super(x); setY(0);}
    public BaseY(int x, int y) {super(x); setY(y);}


    public void shout() {
        System.out.println(y + "!!");
    }
}

我想用新的类BaseXBaseY扩展MyXMyY

class MyX extends BaseX {
    public MyX(int x) {super(x);}

    @Override
    public void say() {super.say(); System.out.println("(MyX)");}
    public void printValue(int z) {
        System.out.println("value: " + z + " - x: " + getX());
    }
}

但这是问题所在。接下来是什么?是否扩展MyXBaseY?在这种情况下 看来我需要同时扩展两者:

class MyY extends MyX, BaseY {
    // impossible. how to do this?
    public MyY(int x) { (MyX super)(x);}
    public MyY(int x, int y) { (BaseY super)(x, y);}

    @Override
    public void say() {(MyX super).say(); System.out.println("(MyY)");}
    @Override
    public void printValue(int z) {(MyX super).printValue(z); System.out.println("(MyY)");}
}

然后我将像这样使用MyXMyY

MyX mX = new MyX(1);
MyY mY = new MyY(2, 3);

assert mY instanceof MyX; // MyY is a subclass of MyX, so this works.
assert mX instanceof X; // BaseX implements `X`.
assert mY instanceof X; // ...so mY should too.

mX.setX(5);
mX.getX(); // 5
mX.say(); // 5 (MyX)
mX.printValue(10); // value: 10 - x: 5

mY.setX(15);
mY.getX(); // 15
mY.say(); // 15 (MyX) (MyY)
mY.printValue(10); // value: 10 - x: 15 (MyY)
// mY inherits from BaseY, so this works:
mY.shout(); // 15!!

我尝试创建所有默认方法的接口:

interface BaseXMethods extends X {
    public default void say() { System.out.println(getX()); }
}

interface BaseYMethods extends Y { ... }

class BaseX implements BaseXMethods {
    ...
}

class MyY extends MyX implements BaseYMethods { ... }

但是我仍然需要实现getter,setter和构造函数,这很繁琐:

class BaseX implements BaseXMethods {
    private int x;
    public BaseX(int x) {setX(x); /* or maybe call an init method from superinterface */}

    public int getX() {return x;}
    public int setX(int x) {this.x = x;}
}

class BaseY extends BaseX implements BaseYMethods {
    private int y;
    public BaseY(int x) {super(x); setY(0);}
    public BaseY(int x, int y) {super(x); setY(y);}

    public int getY() {return y};
    public void setY(int y) {this.y = y;}
}

有更好的方法吗?

0 个答案:

没有答案