java - 是否可以恢复父类的重写方法?
问题描述
我现在正在玩物体,当我为了可读性而骑车时注意到了一些东西。 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()
能通过类型转换调用?
解决方案
无论我使用什么类型的引用,似乎都为构建它的类调用了 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
推荐阅读
- python - param-grid 将参数传递给底层函数。迷失在 kw_args
- python-3.x - 是否可以在 spaCy 中排除某些 POS 标签?Python
- segmentation-fault - 分段故障运动检测 Opencv4tegra
- json - 在构建和部署 SyntaxError 后反应 firebase 错误:预期的表达式,得到 '<'
- android - 使用 jfeaturelib 计算 Haralick 特征
- mysql - SELECT 具有不同的外键值
- angular - 保持页面状态并导致 Angular 5 与浏览器后退按钮一起使用
- xslt - 根据属性和值删除重复元素
- flutter - GestureDetector 中的 SingleChildScrollView 不起作用
- xamarin.forms - FreshMvvm 绑定和对象状态