我无法弄清楚访问使用基类(对象)的对象的静态类型访问的子类的方法与使用子类(点)所访问的子类的方法之间的区别。
例如:
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()来访问和覆盖方法的好处。它看起来更加复杂,并且该对象只能用于访问基类中子类中方法的实例,而不能访问子类中的任何其他方法。
public boolean equals(Point p){
...
}
上面的方法与equals(Object)
共享名称无关equals
。它不会覆盖它,不能从Object
-typed变量调用它,没有由定义的协定Object
。
当你写
op.equals(p);
您正在调用该Object
类型的方法。该equals
类型中唯一调用的方法是,equals(Object)
并且此选择是永久的。运行时只能提供的不同替代equals(Object)
,但绝不会将调用路由到equals(Point)
。
同样,当你写
p.equals(op);
编译器会再次看到你调用equals
带参数,其静态类型Object
,选择equals(Object)
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句