sách gpt4 ăn đã đi

java - 父/子方法覆盖

In lại 作者:搜寻专家 更新时间:2023-11-01 02:43:53 26 4
mua khóa gpt4 giày nike

考虑以下两个具体loại:

public class A {
protected void foo() {
System.out.println("A foo");
thanh();
}

protected void bar() {
System.out.println("A bar");
}
}

public class B extends A {
@Ghi đè
protected void foo() {
super.foo();
System.out.println("B foo");
}

@Ghi đè
protected void bar() {
System.out.println("B bar");
}
}


lớp công khai Kiểm tra {

public static void main(String[] args) {
B b = new B();
b.foo();
}
}

输出将是:

A foo
B bar
B foo

Đây là正确的。但是,如果我们需要的结果是:

A foo
A bar
B foo

我们phải覆盖这两个方法。

在 Java 对象模型中有什么解决方案吗?

câu trả lời hay nhất

你应该使用组合而不是继承。例如

lớp công khai Kiểm tra {
public static void main(String[] args) {
B b = new B(new A());
b.foo();
}
}

class A implements Parent {
public void foo() {
System.out.println("A foo");
thanh();
}

public void bar() {
System.out.println("A bar");
}
}


interface Parent {
void foo();
void bar();
}

class B implements Parent {

Parent wrapped;

public B(Parent p) {
this.wrapped = p;
}

@Ghi đè
public void foo() {
wrapped.foo();
System.out.println("B foo");
}

@Ghi đè
public void bar() {
System.out.println("B bar");
}

}

关于java - 父/子方法覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27074793/

26 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress