繁体   English   中英

Java从内部对象引用外部对象

[英]java reference to the outer object from inner object

JAVA

public class A {
  string amountA;
  B b;
}

public class B {
  string amountB;

   public void setValue(String value) {
      amountB = value;       

另外,我需要设置amountA = value;。 可能吗? 查看主要方法

      }
}

... main(String... args) {
   A a = new A();
   B b = a.getB(); // b is a member of A
   b.setValue("25") // this should also change 'amountA' in object 'a' to '25'
}

如果需要将valueAValueB设置为相同的value ,则在A类中有A可以同时设置两个value的设置器会更有意义:

   public void setValue(String value) {
      amountA = value; 
      b.setValue(value);
   }

您不能从B的实例中访问A的实例,因为B不是A的内部类。您可以创建与B的任何实例都不相关的B的实例。

public class A {

    public class B {
        string amountB;

        public void setValue(String value) {
            amountB = value;       
            amountA = value; // Using A.this.amountA
        }
    }

    string amountA;

    public B createB() {
        return new B(); // Provides A.this to the B instance.
    }
}

... main(String... args) {
    A a = new A();
    B b = a.createB(); // b is created inside A
    b.setValue("25") // this should also change 'amountA' in object 'a' to '25'
}

您可以使用内部类。

类本身应该更好地创建实例,以便将A.this设置为b

另外

B b = a.new B();

但是我从来没有使用过。

内部类对于有权访问其容器类的容器元素是实用的。

另一种解决方案是在A中使用B对象作为参数来构造一个方法。

听起来您想让A从B 派生而不是包含 B的实例。这样,A的实例中的valueA和与该A的实例相关联的B的实例中的valueA实际上是同一变量。 您还可以通过在A中进行声明来在A中拥有不与B共享的数据。例如,

public class A extends B {
   public String amountAonly; // a string in A that's not in B
   public B getB() { return (B)this; } // typecast to treat A like B
}

public class B {
   public String amountA; // a string that's in both A and B
   public void setValue(String value) {
      amountA = value;
   }
}
...
   main(String[] args) {
       A a = new A();
       B b = a.getB(); // b is the B associated with a
       b.setValue("25"); // will also change 'amountA' in object 'a' to '25'
    }

暂无
暂无

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

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