简体   繁体   English

在对象B中,如何访问已创建对象B的对象A?

[英]Within object B, how to access an object A that has created object B?

My code is of the form below: 我的代码的形式如下:

public class Outer {

    protected int data;
    protected Inner inner;

    protected void run() {
        inner = new Inner();
    }

}

public class Inner extends Outer {

    protected getOuterData() {
        ...
    }
}

An Inner object will only be created within a method of class Outer . Inner对象将仅在类Outer的方法中创建。 Within an Inner object, is there a way to access the data of an instance of class Outer that has created the Inner object? Inner对象中,是否可以访问创建了Inner对象的Outer类实例的数据?

EDIT: I realise that you can just pass the outer object into the inner object via a constructor but I was wondering if there was another way? 编辑:我意识到您可以通过构造函数将外部对象传递给内部对象,但我想知道是否还有另一种方法?

EDIT2: Actually passing the object via the constructor will be OK for what I'm doing. EDIT2:实际上,通过构造函数传递对象对于我在做什么是可以的。

public class Outer {

    protected int data;
    protected Inner inner;

    protected void run() {
        inner = new Inner(this);
    }

}

public class Inner extends Outer {
    private Outer parent;
    Inner(Outer parent) {
        this.parent = parent
    }

    protected getOuterData() {
        return parent;
    }
}

May be this will help you. 可能会对您有帮助。

public class Outer {

    protected int data;
    protected Inner inner;

    protected void run() {
        inner = new Inner();
    }

}

public class Inner extends Outer {

    protected void getOuterData() {
        Outer out = new Outer();        // Create instance of `Outer`
        out.run();                      // Create instane of `Inner`
        Inner inner = out.inner;        // Access data from Outer instance
        int data = out.data;            // Access data from Outer instance
    }
}

public class Outer { 公共课外{

protected int data;
protected Inner inner;

protected void run() {
    inner = new Inner();
}

} }

public class Inner extends Outer { 公共类内部扩展外部{

protected getOuterData() {
    ...
  int localData = data;\\if not already defined with same name
  int localData = super.data;\\if already defined with same name in Inner
}

} }

PS: I think you are doing something wrong by creating Child class object in parent class method. PS:我认为您通过在父类方法中创建Child类对象来做错了。 it may go in infinite loop for creating objects when you initialise child, it will create parent object, which intern create child and so on. 当您初始化子对象时,它可能会陷入无限循环中以创建对象,它将创建父对象,而后者将创建子对象,依此类推。

To avoid this make sure not to use run in constructor. 为了避免这种情况,请确保不要在构造函数中使用run。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM