Java:从不相关的类访问公共成员?
以下 Java 代码是我需要的代码的精简示例。我的问题是,如何从 Second 类内部访问 someInt ?请注意,Second 实现了另一个类,因此我不能只传递 someInt 进去。
package test1;
public class First {
public int someInt;
public static void main(String[] args) {
First x = new First();
}
public First(){
someInt = 9;
Second y = new Second();
}
}
class Second implements xyz{
public Second(){}
public void doSomething(){
someInt = 10; // On this line, the question lies.
System.out.println(someInt);
}
}
The following Java code is a stripped down example of the code I need. My question is, how do I access someInt from inside class Second? Note that Second implements another class, so I can not just pass someInt in.
package test1;
public class First {
public int someInt;
public static void main(String[] args) {
First x = new First();
}
public First(){
someInt = 9;
Second y = new Second();
}
}
class Second implements xyz{
public Second(){}
public void doSomething(){
someInt = 10; // On this line, the question lies.
System.out.println(someInt);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您无法访问
Second
中First
的someInt
字段,因为Second
不是Second
的内部类代码>首先。以下更改将解决您的问题。You can't access
First
'ssomeInt
field inSecond
becauseSecond
isn't an inner class ofFirst
. The changes below would fix your problem.如果您需要访问
First
中的字段(而不是在Second
中创建新字段),则需要传递对First
实例的引用code> 当您创建Second
的实例时。根据您的问题“从不相关的类访问公共成员”,问题是通过创建关系来解决的。如果不允许,这个答案就是错误的。
If you need to access the field in
First
(and not create a new one inSecond
), you need to pass a reference to the instance ofFirst
when you create the instance ofSecond
.In the terms of your question, "Access public member from a non-related class", the problem is solved by creating a relation. If that isn't allowed, this answer is wrong.
访问公共成员遵循与访问公共方法相同的语法规则(只是没有括号)
但是在类中拥有公共成员通常不是一个好主意
Accessing a public member follows the same syntax rules as accessing a public method (just without the brackets)
But having a public member in a class is usually not a good idea
最直接的方法是
1) 实例化 First
2) 直接访问它,因为您将实例变量 someInt 设为 public
更好的方法是为 First 中的 someInt 提供访问器,并以这种方式执行。
The most direct way would be to
1) instantiate First
2) access it directly because you made the instance variable someInt public
A better way would be to provide accessors for someInt in First, and do it that way.
在你的第二类中,你必须有一个第一类对象。在第二个类中创建该对象,然后您将能够访问 someInt。
Within your second class, you must have a first class object. Create that object in your second class, then you will be able to access someInt.
您需要获取对 First 的实例的引用,因为
someInt
不是静态的。You need to get a reference to an instance of
First
sincesomeInt
is not static.