gpt4 book ai didi

java - 从外部类修改基类中的内容并从派生类访问它

转载 作者:太空宇宙 更新时间:2023-11-04 08:09:27 25 4
gpt4 key购买 nike

我有一个基类、一个派生类和另一个外部类。我尝试从外部类更新基类中的值,并且从派生类访问它。

我的类结构如下:

class B:{

bool flag;

setFlag(bool value){
flag = value;
}
printFlag(){
print flag;
}

ExternalClass e = new ExternalClass(this);
}

class External {
B b = null;
External( B b){
this.b = b;
}
b.setFlag(true);

}

Class Derived : extends B{

printFlag();
}

这里虽然我已将标志设置为 true,但 print 方法打印 false。我不知道发生了什么。请帮助我。

Description Image

最佳答案

下面是一些可以实现您想要的功能的代码:

class Derived extends B{
public Derived(){
super();
// this is the important bit, by calling super() you call the parent classes
// constructor, which in this case changes the attribute "flag"
// by using the constructor of the external class on the class
}
}

class B {
boolean flag;
ExternalClass e;

public B(){
e = new ExternalClass(this);
}

public void setFlag(boolean value) {
flag = value;
}

public void printFlag() {
System.out.println(flag);
}

}

class ExternalClass {

B b = null;

public ExternalClass(B b) {
this.b = b;
b.setFlag (true);
}
}

关于java - 从外部类修改基类中的内容并从派生类访问它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11473775/

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