开发者

How could I add this attribute?

开发者 https://www.devze.com 2023-04-08 19:41 出处:网络
I have a class that is called ShapeBase. It is abstract and draw method must be implemented. It has instance variables for things like width and height. From this, Circle, Line, and Rectangle are subc

I have a class that is called ShapeBase. It is abstract and draw method must be implemented. It has instance variables for things like width and height. From this, Circle, Line, and Rectangle are subclasses and implement the draw method. The Line class does not have an isFilled property (get / set) but Rectangle, and Circle do. I could obviously just add the property to both separatly, but later on I may want to dynamically gather all shapes that can be 'filled'. I thought of making a filled interface but, the problem is then I have to implement the getter and setter for both. In C++ I'd make use of multiple inheritance to solve this, but what can I do i开发者_如何学JAVAn Java to solve this kind of problem?

Thanks


You could have a FillableShapeBase which is abstract and extends ShapeBase but has the added isFilled property with getters and setters. Rectangle and Circle could inherit from FillableShapeBase.


public abstract class FillableShape extends Shape {
    // isFilled
}

public class Circle extends FillableShape {
   ....
}

public class Rectangle extends FillableShape {
   ....
}


Why not simply make FilledShape an abstract class that inherits from ShapeBase and implements isFilled?

0

精彩评论

暂无评论...
验证码 换一张
取 消