简体   繁体   中英

How do I ensure the type of a generic method in my implementation?

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?

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()
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM