gpt4 book ai didi

java - 使用父类(super class)中已在子类中重写的方法,具体取决于调用它的对象的类型

转载 作者:行者123 更新时间:2023-12-02 04:19:06 25 4
gpt4 key购买 nike

我正在寻找一种方法来根据调用该方法的对象的类型来调用(重写)方法的不同定义。当我研究下面的观点时,这应该更有意义。

我有两个类定义如下:

public class SuperClass{

public method1(){
if (objects are of type SuperClass and not SubClass){ //pseudocode
method2();
}
//do some more stuff
}

public method2(){
//do stuff
}
}

public class SubClass extends SuperClass{

@Override
public method1(){
method2();
super.method1();
}

@Override
public method2(){
//do stuff
}

}

在这两个类中,我正在处理 3 个对象,将它们称为 dogcatbirddogcat 都是 SuperClass 类型的对象,而 birdSubClass 类型的对象>.

您注意到所有对象在代码中都遵循相同的基本过程,它们的 method1() 在执行其他操作之前调用 method2()。它们之间的区别显然是 SubClass 重写了 method2():bird 有不同的 method2()

目前我的代码正在按我想要的方式工作,但我正在寻找一种更优雅的解决方案(如果有的话)。您可以从上面的代码中看到我是如何解决当前问题的:在 SuperClass 中,我基本上检查对象的类型是否为 SuperClass。在我的实际程序中,伪代码行看起来更像这样(仍然是“伪代码”):

 if(this.toString().equals("Dog") || this.toString().equals("Cat")){
method2();
}

并且bird在调用method1()的原始定义之前调用它自己的method2()定义。基本上,这两个类都在处理它们自己的 method2() 本地定义。

我的更优雅的想法如下:从SubClass中完全删除method1()的重写定义,并能够调用的重写定义method2() 在适当的时间(即当我正在处理的对象是 bird 时)从 SuperClass 中调用。

我基本上完全按照我写的那样尝试了上面的内容,但是bird对象最终使用了SuperClass中的method2()的定义code> 而不是 SubClass 中的代码。

可以这样做吗?如果可以,怎么做?

最佳答案

继承和覆盖完全按照您想要的方式工作,而无需检查实例是父类(super class)还是子类。

就这样吧,

public class SuperClass{
public method1(){
method2(); // Note that you don't need any instance check here.
//do some more stuff
}

public method2(){
SOP("Super method2");
}
}

public class SubClass extends SuperClass{
@Override
public method2(){ // Note that you don't have to override method1
SOP("SUB method2")
}
}

在这种情况下,如果您使用 Super 类对象调用 method1() ,它将调用父类(super class)的 method2() 并打印 Super method2 .

如果您使用子类对象调用method1(),它将调用子类的method2()并打印Sub method2 .

关于java - 使用父类(super class)中已在子类中重写的方法,具体取决于调用它的对象的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32983975/

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