2016-10-04 98 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++模板。你必須非常具體地使用泛型類型。

相關問題