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.