2016-10-04 100 views
1

我不确定如何运行通用类型Point的方法。假设以下类通用类型的运行方法

class Point1 { 
     double x, y; 
     public Point1 (double x_, double y_) {x=x_; y = y_;} 
     public double getX() {return x;} 
     public double getF1() {return x;} 
} 

class Point2 { 
     double lat, lon; 
     public Point2 (double lat_, double lon_) {lat = lat_; lon = lon_;} 
     public double getLat(){return lat;} 
     public double getF1() {return lat;} 
} 

共享相同的方法getF1()和一个方法

public <Point> void test(List<Point> points) { 
    for (Point point:points) 
     double x = point.getF1(); //Error Can not find symbol getF1() 
} 

public static void main (String [args]) { 
    List <Point1> points = new ArrayList<>(); 
    test(points); 
} 

如何运行与POINT1类型为普通类型点(POINT = POINT1相关联的方法getF1() )?是否有可能使用的接口

public interface ICoord { 
    double f(); 

public <Point> void test(List<Point> points, ICoord function) { 
    for (Point point:points) 
     double x = point.function.f(); 
} 
+0

'Point1'和'Point2'必须有一些通用的超类或接口才能够一般地引用它们。 – Taylor

+1

什么是'Point'?没有看到它的定义。 –

+0

@Sabir:这里Point = Point1 – justik

回答

3

它看起来像你只是缺少的Point的定义在这里。

public interface Point { 
    double getF1(); 
} 

这也意味着,每个Point类必须实现这个接口:

public class Point1 implements Point { } 
public class Point2 implements Point { } 

...然后你可以使用它,但你不会需要泛型参数在所有。

public void test(List<Point> points) { 
    for (Point point: points) { 
     double x = point.getF1(); 
    } 
} 
+0

删除循环中的评论,这可能会引起误解;) – AxelH

+1

@AxelH:好的;如果你在答案中看到类似的东西,不要害羞建议编辑。我会批准那个。 – Makoto

1

首先,你需要提取getF1()方法:

private interface PointWithF1 { 
    public double getF1(); 
} 

private static class Point1 implements PointWithF1 { 
    // ... 
} 

private static class Point2 implements PointWithF1 { 
    // ... 
} 

然后,你可以定义一个绑定的泛型类型:

public <Point extends PointWithF1> void test(List<Point> points) { 
     for (Point point : points) { 
      double x = point.getF1(); //Okay now 
     } 
} 

但是,那么,你可以简单的使用界面太:

public void test(List<PointWithF1> points) { 
     for (PointWithF1 point : points) { 
      double x = point.getF1(); //Okay now 
     } 
} 

所以重点是(没有双关语意思),java泛型不能做所有那些编译时类型检查作为C++模板。你必须非常具体地使用泛型类型。

相关问题