多继承java

时间:2016-02-24 23:11:37

标签: java inheritance multiple-inheritance

我正在一个有这些课程的项目中工作:

public class Rectangle {
    public void printMe() {
        print("I am a Rectangle");
    }
}

public class Square extends Rectangle {
    @Override
    public void printMe() {
        print("I am a Square");
    }
}

public class RedRectangle extends Rectangle {
    @Override
    public void printMe() {
        super.printMe();
        print(" and I am red");
    }
}

这些类别的coures有其他方法和属性。

我想创建另一个继承Rectangle中所有属性和方法的类RedSquare,但它还需要使用Square类中的方法覆盖自己的方法。它将打印"我是一个Square,我是红色",使用RedRectangle和Square类的代码。

它应该能够使用Square和RedRectangle中的方法,否则它应该使用Rectangle中的方法,它应该强制开发人员从他自己的代码中写入所有那些已被覆盖的方法Square和RedRectangle。

我实际上知道这是多重继承而Java并不支持它,但我需要实现这种行为。

我尝试使用Square和RedRectangle作为私有属性来实现它,无论如何,如果我调用某个方法RedRectangle.myMethod()在内部调用另一个方法,它将使用本身存在的实现(或最终在超级矩形中)和不是在RedSquare(或最终在Square中)被覆盖的地方。

是否有任何有用的模式可以用于最大量的代码重用? 你会如何实现这个?

非常感谢。

1 个答案:

答案 0 :(得分:1)

当您想要矩形的颜色时,您正在使用的是矩形的属性,而不是矩形的子类型。在这里,你应该支持组合而不是继承,创建一个ColorOfShape类,它可以是Rectangle的属性。

class Rectangle {
    ColorOfShape color;
    void printMe() { printMeOnly(); printColor(); }
    void printMeOnly() { print("I am a Rectangle"); }
    void printColor() { color.printMe(); }
}
class Square extends Rectangle {
    @Override void printMeOnly() { print("I am a Square"); }
}

abstract class ColorOfShape {
    abstract void printMe();
}
class RedColor extends ColorOfShape {
    @Override void printMe() { print(" and I am red"); }
}