How to design this following structure in Java?
I have an interface named SHAPE
. CIRCLE
and RECTANGLE
are two cla开发者_高级运维sses implementing this interface. Now I have to write a class (i have an option to write a class only) CIRCULARRECTANGLE
which will extend the properties of CIRCLE
and RECTANGLE
. How to do this in Java?
You can't do this directly. A Java class can always only extend a single class.
You could use delegation to get a similar effect. Your CircularRectangle
(whatever that may represent!) could reference a Circle
and a Rectangle
object and "present" their properties as its own.
We can't define a class that is-a Circle
and a Rectangle
- as long as both entities are classes.
To solve a problem where this kind of schizophrenic behaviour is desired, we can consider using the adapter pattern (assuming, we have a Circle and Rectangle interface and concrete implementations)
public class CircleImpl implements Circle {
// fields, constructors, implemented Circle methods
public Object adapt(Class<? extends Shape> adaptee) {
if (adaptee == Rectangle.class) {
return new Rectangle() {
// implemented rectangle methods so that
// we have a squared circle
};
}
return null;
}
}
Since Java extends one class at a time, you will need to create abstract classes to fit your criteria.
Example:
public abstract class AbstractRectangle extends Rectangle {
public abstract class AbstractCircularRectangle extends AbstractRectangle {
public class CircularRectangle extends AbstractCircularRectangle {
Update: My first attempt will never work, hence my update:
Since my first attempt never extended a Circle
, you will need to keep reference to eiter a Circle
or a Rectangle
like so:
public class CircularRectangle extends Rectangle {
private Circle circle;
public CircularRectangle(Circle circle) {
this.circle = circle;
}
// Some logic:
}
The purpose of the constructor is to keep reference to a circle.
Java does not allow multiinheritance,perhaps you can do in using composition :
CIRCULARRECTANGLE
implements SHAPE
.
CIRCULARRECTANGLE
also contains an instance of CIRCLE
and RECTANGLE
.Then you implement the methods of CIRCULARRECTANGLE
using this two instances according to your logic.
I would define 2 interfaces Circle and Rectangle. You classes will implement these interfaces. Then you can define interface CircularRectangle extending both interfaces. The tridr class CircularRectangle should have 2 instances cirlceInstance and rectangleInstance and delegate calls invoking necesary methods from the instances.
As java doesn't allow multiple inheritance, this is just not possible. You cannot let a class extend more than one superclass. Try using composition instead of inheritance.
精彩评论