gpt4 book ai didi

java - 使用组合

转载 作者:行者123 更新时间:2023-12-01 15:43:33 26 4
gpt4 key购买 nike

我正在尝试使用自定义类来使用组合重写其父类(super class)中的方法。下面是我尝试的代码,在“Bar”类中什么对象调用方法 doSomethingElse() ?这不是我的代码,并链接到问题 - Using composition over inheritance when overriding

所有实例化都在子类中进行。

class Child extents Parent(){

public Child(){
super();
addButtons():
}
addButtons(){
<custom code here>
}

}


class Parent(){
addButtons(){
add(button1);
}
}
<小时/>
interface SomeMethods {
void doSomething();
void doSomethingElse();
}

class Foo implements SomeMethod {
public void doSomething() { // implementation }
public void doSomethingElse() { // implementation }
}

class Bar implements SomeMethod {
private final Foo foo = new Foo();

public void doSomething() { foo.doSomething(); }
public void doSomethingElse() { // do something else! }
}

最佳答案

你已经很接近了,只需使用 Bar 类执行此操作即可

class Bar extends Foo {
// note Bar is still of type SomeMethods because it extends a class of that type.
public void doSomething() {
super.doSomething();
//add more code here if you want to do some more stuff, note you don't need to define this function if you don't need to do anything else.
}
public void doSomethingElse() {
//don't call super, and do whatever you like
}
}

关于java - 使用组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7585572/

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