繁体   English   中英

Java如何在外部类的实例中访问另一个类的实例的属性?

[英]Java how to access the property of instance of another class in the instance of outer class?

我可能使用了不正确的术语,在此先抱歉。 我需要从位于外部类的实例中的另一个类的实例访问属性。 将有两个类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?

}

}

Inner2类需要为Inner1具有实例属性

public class Inner2{

private Inner1 inner1;

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

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

}

首先在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
}

}

暂无
暂无

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

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