【问题标题】:Java how to access the property of instance of another class in the instance of outer class?Java如何在外部类的实例中访问另一个类的实例的属性?
【发布时间】:2013-01-23 07:06:13
【问题描述】:

我可能会使用不正确的术语,提前抱歉。 我需要从位于外部类实例中的另一个类的实例访问属性。将有两个 Outer 类实例,我需要分别为每个实例存储和处理属性“desiredProperty”。 注意:所有班级都不一样。 Inner1 和 Inner2 不是同一个类! 这是一个简单的例子。

文件 1:

public class Outer{

public Inner1 inner1 = new Inner1();
public Inner2 inner2 = new Inner2();

}

文件 2:

public class Inner1 {

int desiredProperty=1;

}

文件 3:

public class Inner2{

public int getDesiredProperty(){

//How can I here access the property DesiredProperty from Inner1?

}

}

【问题讨论】:

  • 你需要有一个Inner1实例的引用。这些类是否以任何方式相关(或仅称为外部和内部)?

标签: java class instance


【解决方案1】:

Inner2 类需要有 Inner1 的实例属性

public class Inner2{

private Inner1 inner1;

public Inner2(Inner1 inner1){
   this.inner1 = inner1;
}

public int getDesiredProperty(){
    return inner1.getDesiredProperty();    
}

}

【讨论】:

    【解决方案2】:

    首先在 Inner1 类中创建一个 setter getter 函数,这样你就可以获取/设置 Inner1 上的值

    public class Inner1 {
    
    int desiredProperty=1;
    public int getDesiredProperty()
    {
        return this.desiredProperty;
    }
    
    public void setDesiredProperty(int val)
    {
        this.desiredProperty = val;
    }
    
    }
    

    在 Inner2 类中

    public class Inner2{
    
    public int getDesiredProperty(){
    
    //How can I here access the property DesiredProperty from Inner1?
    Inner1 inner1 = new Inner1();
    return inner1.getDesiredProperty(); //value from Inner1
    }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多