-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.

3
  • 2
    You could use interfaces...You can implement multiple interfaces in Java. Commented Feb 24, 2016 at 23:14
  • 2
    Don't explain the problems in your code without also posting the code that has a problem. Commented Feb 24, 2016 at 23:15
  • you can do something like this in java 8. Commented Feb 25, 2016 at 0:35

1 Answer 1

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"); }
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.