-2

I am working in a project where I have these classes:

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");
    }
}

These classes, of coures, have others methods and attributes.

I would like to create another class RedSquare that inherits all attributes and methods from Rectangle, but it needs also to override its own methods with those present in the Square class. It will print "I am a Square and I am red", using the code from both RedRectangle and Square classes.

It should be able to use the methods from Square and RedRectangle if it can, otherwise it should use methods from Rectangle, and it should force the developer to write from his own the code for all those methods that have been overridden in both Square and RedRectangle.

I actually know that this is multiple inheritance and Java doesn't support it, but I need to implement this kind of behaviour.

I tried to implement this using Square and RedRectangle as private attributes, anyway if I call certain method RedRectangle.myMethod() that calls internally another method, it will use the implementation present in itself (or eventually in the super Rectangle) and not in RedSquare (or eventually in Square) where it was overridden.

Is there any useful pattern that I can use with the maximum amount of code reuse? How would you implement this?

Thanks a lot.

Stefan Dollase
  • 4,530
  • 3
  • 27
  • 51
Jody
  • 101
  • 3
  • 2
    You could use `interfaces`...You can implement multiple `interfaces` in `Java`. – brso05 Feb 24 '16 at 23:14
  • 2
    Don't explain the problems in your code without also posting the code that has a problem. – JB Nizet Feb 24 '16 at 23:15
  • you can do something like this in [java 8](http://stackoverflow.com/questions/7857832/are-defaults-in-jdk-8-a-form-of-multiple-inheritance-in-java). – Ray Tayek Feb 25 '16 at 00:35

1 Answers1

1

What you're working with when you want a color for a rectangle is an attribute of the rectangle, not a subtype of a rectangle. Here, you should favor composition over inheritance, creating a ColorOfShape class that can be an attribute of 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"); }
}
rgettman
  • 176,041
  • 30
  • 275
  • 357