有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

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

我的班级结构如下:

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


共 (1) 个答案

  1. # 1 楼答案

    下面是一些代码,可以实现您的愿望:

    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);
        }
    }