【问题标题】:creating an object with static type of base class vs subclass?创建具有静态类型的基类与子类的对象?
【发布时间】: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 不是术语。 overrideoverload 又是两个不同的东西。

标签: java object polymorphism extend


【解决方案1】:
public boolean equals(Point p){
  ...
}

上述方法除了共享名称equals外,与equals(Object)无关。它不会覆盖它,它不能从 Object 类型的变量中调用,Object 没有定义它的契约。

当你写作时

op.equals(p);

您正在调用Object 类型的方法。在该类型中称为equals 的唯一方法是equals(Object),此选择是永久。运行时只能提供对equals(Object) 的不同覆盖,但它永远不会将调用路由到equals(Point)

同样,当你写作时

p.equals(op);

编译器将再次看到您正在使用静态类型为Object 的参数调用equals,选择equals(Object)

【讨论】:

  • 啊!谢谢你澄清这一点。我知道 object op 只能覆盖具有 Object 类型作为参数的子类中的 equals() 方法,但我错过了明显的一点,这正是我们需要创建另一个静态类型 Point 的对象来访问任何其他 equals 的原因() 方法,不是子类 Point 中的 Object 类型参数。
【解决方案2】:

我认为你搞砸了一些概念,所以让我解释一下:

Object op = new Point(3,4);

变量op 的行为很清楚,所以我将重点关注op:它是一个类型为Object 的变量,这意味着您可以使用该类中声明的所有方法。您不能使用 equals(Point p) 方法,因为它不存在用于 Object。但是,与此同时,方法的行为是由它自己的实例给出的,而不是由指向它的变量给出,所以op 指向一个 Point 实例,equals(Object) 方法已被覆盖,所以该方法的行为由 Point 类给出。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-28
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 2022-08-19
    • 1970-01-01
    相关资源
    最近更新 更多