【发布时间】:2014-04-04 13:35:09
【问题描述】:
我无法弄清楚访问子类的方法之间的区别,该方法使用对象的静态类型的基类 (Object) 访问和覆盖与使用子类 (Point)。
例如:
public class Point {
int x, y;
...
public boolean equals(Object o){
...
}
public boolean equals(Point p){
...
}
}
Object o = new Object();
Point p = new Point(3,4);
Object op = new Point(3,4);
// here the static type is Point and the dynamic type is point, in this case
// the equals() method that we choose and gets overwrriten depends on the
// parameter type that is passed.
p.equals(o);
p.equals(p);
p.equals(op);
// here however the static type is Object so we initially look at the equals()
// method in our Object class during compile time and check its parameter type
// which is Object, thus if we overwrite
// the equals() method we will pick the one that has a type Object parameter.
// Since the dynamic type of our object is Point, when we are at run time
// we will look for the equals() method in Point that matches with the
// method type Object parameter.
op.equals(o);
op.equals(op);
op.equals(p);
我没有看到的是为什么我要使用后者而不是前者来指定我想要覆盖的方法?前者依赖于类型参数,而后者依赖于我们对象的静态类型的类型参数。我只是看不到使用 Basetype obj = new Subclasstype() 访问和覆盖我的子类中的方法的好处。它看起来更复杂,并且该对象只能用于访问基类中的子类中方法的实例,而不能访问子类中的任何其他方法。
【问题讨论】:
-
请注意,overwrite 不是术语。 override 和 overload 又是两个不同的东西。
标签: java object polymorphism extend