我有一個有一個普通方法和一個通用方法的接口。我已經爲兩個不同的類實現了普通的方法,但是現在不用如何用泛型方法來實現。這裏是我的代碼:如何在java中爲兩個類實現一個通用方法
Sphere.java:
public class Sphere implements GeometricShape<Sphere> {
private double radius;
public Sphere (double radius) {
this.radius = radius;
}
public double volume() {
return (4.0/3.0) * Math.PI * radius * radius * radius;
}
public void describe() {
System.out.println("Sphere[radius=" + radius + "]");
}
@Override
public Sphere supersize()
{
this.radius*=2;
return new Sphere(radius);
}
}
Rectangle.java
public class Rectangle implements TwoDShape {
private double width, height;
public Rectangle (double width, double height) {
this.width = width;
this.height = height;
}
public double area()
{
return width * height;
}
public double perimeter()
{
return 2.0 * (width + height);
}
public void describe()
{
System.out.println("Rectangle[width=" + width + ", height=" + height + "]");
}
@Override
public Rectangle supersize()
{
this.width*=2;
this.height*=2;
return new Rectangle(width, height);
}
}
TwoDShape.java:
public interface TwoDShape extends GeometricShape
{
public double area();
}
ThreeDShape.java:
public interface ThreeDShape extends GeometricShape<ThreeDShape>
{
public double volume();
}
GeometricShape.java:
public interface GeometricShape<T extends GeometricShape<T>>
{
public void describe();
public T supersize();
}
最後主類ArrayListExample.java:
import java.util.ArrayList;
public class ArrayListExample {
public static void describe_all(ArrayList<? extends GeometricShape> shapes)
{
for(int i=0;i<shapes.size();i++)
{
shapes.get(i).describe();
}
System.out.println("Total number of shapes:"+ shapes.size());
}
public static void main(String[] args) {
System.out.println("The describe() method:");
System.out.println();
System.out.println("Example rectangles");
ArrayList<Rectangle> rects = new ArrayList<Rectangle>();
rects.add(new Rectangle(2.0, 3.0));
rects.add(new Rectangle(5.0, 5.0));
describe_all(rects);
System.out.println();
ArrayList<Sphere> spheres = new ArrayList<Sphere>();
spheres.add(new Sphere(10.0));
spheres.add(new Sphere(50.0));
spheres.add(new Sphere(0.0));
System.out.println("Example spheres");
describe_all(spheres);
System.out.println();
System.out.println("The supersize() method:");
System.out.println();
ArrayList<Rectangle> double_rects = supersize_list(rects);
describe_all(double_rects);
System.out.println();
ArrayList<Sphere> double_spheres = supersize_list(spheres);
describe_all(double_spheres);
}
}
我如何能實現supersize_list方法,它需要超大方法從兩個矩形和領域和輸出,如
Rectangle[width=4.0, height=6.0]
Rectangle[width=10.0, height=10.0]
Total number of shapes: 2
Sphere[radius=20.0]
Sphere[radius=100.0]
Sphere[radius=0.0]
Total number of shapes: 3
你能幫我解決這個問題嗎?我非常感謝你的幫助!
我很困惑,爲什麼'supersize'將返回一個新對象的泛型方法,它應該不只是增加現有對象的大小? –
@ScaryWombat我同意,它應該做,但不是兩者。 –
是的,我想在球體和矩形兩次增加大小。你有什麼建議?我想寫一個supersize_list方法,返回尺寸增加的矩形和球體@Scary Wombat @ Luke Lee –