Reputation: 1
This is my first time asking a question here so I hope I post everything correctly.
I'm working on my assignment and I'm a little stuck on this problem. There are four classes of shapes (circle, cone, sphere, and rectangle) that all implement the interface GeometricShape....
public interface GeometricShape {
public void describe();
}
The question says to add a new method called supersize() to the interface, which will take the current shape and return a shape of the same type that is double the size using generics. The hint says to generalize the interface as a start like this...
public interface GeometricShape<T extends GeometricShape<T>> {
public void describe();
public T supersize();
}
so that T can only be a geometric shape. But when done this way, it is possible for Rectangle.supersize() to return a circle. How can I make it so that this doesn't happen (ex. Rectangle.supersize() can only return Rectangle) by only modifying the interface code?
Upvotes: 0
Views: 41
Reputation: 364
The trick is not in the interface definition but in the class declarations.
For rectangle, define it as such:
public class Rectangle implements GeometricShape<Rectangle> {
public void describe() {// do stuff}
public Rectangle supersize() {
return new Rectangle()
//this should fail since you have specified T
//return new Circle()
}
}
Upvotes: 1