作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
以下是涉及抽象方法和重写的流行用例。
class Demo {
public static void main(String[] args) {
Parent a = new Child_A();
Parent b = new Child_B();
a.method();
b.method();
}
}
abstract class Parent {
abstract void method();
}
class Child_A extends Parent {
@override
void method() {
do the task for Child_A;
}
}
class Child_B extends Parent {
@override
void method() {
do the task for Child_B;
}
}
看来我们总是可以通过在父类(super class)中定义一个泛型方法来实现同样的事情,该方法使用instanceof
关键字来确定子类并为子类执行相应的任务。
class Demo {
public static void main(String[] args) {
Parent a = new Child_A();
Parent b = new Child_B();
a.method();
b.method();
}
}
class Parent {
void method() {
if (this instanceof Child_A) {
do the task for Child_A;
}
else if (this instanceof Child_B) {
do the task for Child_B;
}
}
}
class Child_A extends Parent {
}
class Child_B extends Parent {
}
哪种代码风格更好,为什么?
最佳答案
因为:
关于java - 当我们总是可以在父类(super class)中使用泛型方法时,为什么要费心使用抽象方法和重写呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50183641/
我是一名优秀的程序员,十分优秀!