使用接口在2个java类之间进行通信
我有 2 个 A 类和 B 类。
class A Implements Constants{
private int state;
}
class B implements Constants{
foo(){
//want to set state variable of class A like this
state = state1
}
}
interface Constants{
public final int state1;
public final int state2;
}
我不想在 B 类中拥有 A 类的实例。我应该怎么做? 如果我有一个在接口中设置变量的函数,那么两个类都必须实现该函数。那是错误的吧?因为那么同一个函数的两个定义会发生冲突吗?
I have 2 classes A and B.
class A implements Constants{
private int state;
}
class B implements Constants{
foo(){
//want to set state variable of class A like this
state = state1
}
}
interface Constants{
public final int state1;
public final int state2;
}
I don't want to have an instance of class A in class B. How should I do this?
If I have a function to set the variable in the interface, then both the classes must implement this function. That would be wrong right? Because then 2 definitions for the same function would conflict?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
java中没有什么叫函数。它们是方法。
您可以在类中包含 getter 和 setter,以便从外部类设置和获取属性。
你的问题不清楚。
如果你的B类扩展了A类,那么通过B类的构造函数,你可以设置作为超类的A类的属性。
希望有帮助!
There is nothing called functions in java. They are methods.
You can have getters and setters in your classes for the properties to set and get them from external classes.
Your question is unclear.
If your B class extends the A class, then through the constructor of the B class, you can set the properties of the A class that is the super class.
Hope it helps!
拥有接口并不意味着变量将在类之间共享,它更多的是定义必须覆盖接口中函数的类的一种方式。您可以在此处阅读有关它们的基础知识。要在两个类之间共享变量,您可以将变量设置为静态并将其放入两个类都扩展的另一个类中(实际上是一个全局变量,这是不好的做法并且不是线程安全的),或者让其中一个类具有另一个的实例并调用 getters/setters。
编辑:有一个类似的问题这里< /a> 这向您展示了我对静态变量的含义。
Having an interface does not mean that the variable will be shared between the classes, it is more of a way to define classes that MUST override the functions in the interface. You can read the very basics on them here. To share a variable between two classes, you can either make the variable static and put it in another class that both your classes extend (in effect a global variable, which is bad practice and not thread safe), or have one of the classes have an instance of the other and call getters/setters.
EDIT: there is a similar question here that shows you what I mean about the static variable.
您通常希望避免在类中编写任何尝试更改另一个类的内部状态的方法。无论你想出什么技巧来完成这样的事情,你都打破了封装原则,而这正是使用类的首要原因。
如果您希望从多个类访问某个状态,我建议将该状态分解为它自己的类,并让两个类中的每一个通过 getter/setter 或实用程序方法与其交互。
You generally want to avoid writing any method in a class that attempts to alter the internal state of another class. Whatever trick you come up with to accomplish such a thing, you are breaking the principle of encapsulation which is the whole reason for using classes in the first place.
If there is some state that you wish to have accessible from multiple classes, I would recommend breaking that state out into it's own class and have each of the two classes interact with it through getter/setter or utility methods.