聚合 - 在另一个类的方法中检索另一个类实例变量 [英] Aggregation- retrieving another classes instance variable in a method of another class

查看:79
本文介绍了聚合 - 在另一个类的方法中检索另一个类实例变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我查看了很多来源,但我无法想出如何检索另一个类实例变量以放入另一个类的方法,例如:

I have looked through many sources, but I am unable to come up with a solution as to how I would retrieve another classes instance variable to put in a method of another class for example:

public class Example{
    private ExampleTwo info;

    public void setInfo(int one, int two){   // i am trying to set the parameters so it can access the instance variable from ExampleTwo class

    }

}

public class ExampleTwo{
    private int one;
    private int two;

    //....rest of code

}

推荐答案

请记住,java没有像C#这样的属性。所以你需要在这里玩一点有点棘手。采用属性风格。



当您想要访问私有的类变量时,请编写两个公共方法。请参阅以下示例

Remember, java does not have Property like C#. So you need to play a little tricky here. Adopt the property style.

When you want to access a class variable which is private, write two public methods. see the following example
class Two
{
private int var;

public int getVar()
{
return var;
}

public void setVar(int var)
{
this.var=var;
}
}

class One
{
Two objTwo=new Two();
public void oneMethod()
{
objTwo.setVar(30);
System.out.println(objTwo.getVar());

}
}





请妥善写下您的问题以获得适当的答案。希望这个例子可以帮助您理解您的问题。



Please write your question appropriately to get appropriate answer. Hope this example helps you understand your problem.


这篇关于聚合 - 在另一个类的方法中检索另一个类实例变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆