gpt4 book ai didi

java - 当我们总是可以在父类(super class)中使用泛型方法时,为什么要费心使用抽象方法和重写呢?

转载 作者:行者123 更新时间:2023-12-02 11:17:17 24 4
gpt4 key购买 nike

以下是涉及抽象方法和重写的流行用例。

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 {
}

哪种代码风格更好,为什么?

最佳答案

因为:

  • 您不想每次添加另一个子类时都必须修改父类
  • 在某些情况下,例如库 API,您甚至可能不知道所有子类
  • 处理子类的代码应该位于该子类中,而不是位于父类中。

关于java - 当我们总是可以在父类(super class)中使用泛型方法时,为什么要费心使用抽象方法和重写呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50183641/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com