首页 > 解决方案 > 是否可以恢复父类的重写方法?

问题描述

我现在正在玩物体,当我为了可读性而骑车时注意到了一些东西。 toString()观察这些类和结果。

    class Point {
        int x;
        int y;
        Point(int x, int y) {
            this.x = x; this.y = y;
        }
        public String toString() {
            return String.format("(%d,%d)",x,y);
        }
    }
    class Line extends Point {
        int l;
        Line(int x, int y, int l) {
            super(x,y);
            this.l = l;
        }
        public String toString() {
            return String.format("Length is %d", this.l);
        }
    }
JShell REPL:
> new Point(0,0)
==> (0,0)

> new Line(0,1,4)
==> Length is 4

> Point p = new Line(0,1,3);
p ==> Length is 3

> p.x
==> 0

> p.y
==> 1

> p.l
| Error    //Expected, p is a Point reference

> ((Line) p).l
==> 3

> Line l = (Line) p
l ==> Length is 3

> l.x
==> 0

> l.y
==> 1    //referencing x and y this way were surprising, but it makes sense

> ((Line) p).x
==> 0

> l.l
==> 3

> ((Point) l).toString()
==> "Length is 3"

对象实例必须使用正确的引用来获取所需类中的方法。那么,为什么要toString()区别对待呢?toString()无论我使用的是什么类型的引用,它似乎都是为构建它的类调用的。

编辑:由于toString()被覆盖两次,我怎么Point.toString()能通过类型转换调用?

标签: javaclasscastingtostring

解决方案


无论我使用什么类型的引用,似乎都为构建它的类调用了 toString()。

是的。这就是 Java 中动态调度的全部内容。检查什么是动态方法分派以及它与继承有何关系?了解更多信息。

演示:

public class Main {
    public static void main(String[] args) {
        Point p1 = new Point(10, 20);
        Object p2 = new Point(5, 15);

        Point l1 = new Line(3, 8, 7);
        Line l2 = new Line(10, 20, 20);
        Object l3 = new Line(5, 15, 25);

        System.out.println(p1);
        System.out.println(p2);
        System.out.println(l1);
        System.out.println(l2);
        System.out.println(l3);
    }
}

输出:

(10,20)
(5,15)
Length is 7
Length is 20
Length is 25

推荐阅读