通用类型的运行方法
问题描述:
我不确定如何运行通用类型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();
}
答
它看起来像你只是缺少的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();
}
}
答
首先,你需要提取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++模板。你必须非常具体地使用泛型类型。
'Point1'和'Point2'必须有一些通用的超类或接口才能够一般地引用它们。 – Taylor
什么是'Point'?没有看到它的定义。 –
@Sabir:这里Point = Point1 – justik