gpt4 book ai didi

java - 在子类的方法中本地调用父类(super class)方法时使用 "super"关键字或使用父类(super class)实例?

转载 作者:行者123 更新时间:2023-12-01 22:15:32 25 4
gpt4 key购买 nike

假设我有:

class Superclass {
//fields...

methodA() {...}

methodB() {...}

...
}

class Subclass extends Superclass {
//fields...

methodA() {
// Here I need to call methods A and B from superclass:
// For this, I can use supper
super.methodA();
super.methodB();

// Or I have to instantiate the superclass and use the instance
Superclass superclass = new Superclass();
superclass.methodA();
superclass.methodB();
}

这两种方式都有效,但我想知道哪种更好。这些方法中的任何一种都是不好的编程技术吗?希望您能给我答案和论据。

最佳答案

  super.methodA();

Superclass superclass = new Superclass();
superclass.methodA();

这两次methodA调用工作在不同的实例上,所以它们是完全不同的。 super.methodA() 在当前实例上执行methodAsuperclass.methodA()Superclass 的新实例上执行 methodA,该实例与当前实例无关。

您几乎总是会使用第一个选项。至于第二个选项,创建一个新实例,在该实例上调用一个方法,然后不再对该实例执行任何操作是没有意义的。

关于java - 在子类的方法中本地调用父类(super class)方法时使用 "super"关键字或使用父类(super class)实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31130635/

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