I'm learning OOP and trying to write a simple program that will execute some method every time when a specific varible will change.
(我正在学习OOP,并尝试编写一个简单的程序,该程序将在每次特定变量更改时执行某种方法。)
I have two classes:(我有两节课:)
public class SomeClass {
private OtherClass object;
public OtherClass getObject() {
return this.object;
}
public void setObject(OtherClass object) {
objectChanged();
this.object = object;
}
private void objectChanged() {
System.out.println("Object has changed");
}
}
public class OtherClass {
private int value = 5;
public int getValue() {
return this.value;
}
public void setValue(int value) {
this.value = value;
}
}
The variable objectChanged should be called every time when variable "object" is changed.
(每次更改变量“ object”时,都应调用变量objectChanged。)
My first naive idea was to put the method call inside of set function.(我的第一个幼稚想法是将方法调用放在set函数内部。)
But what if you change the object after you set it?(但是,如果在设置对象后更改了对象怎么办?)
Like this:(像这样:)
SomeClass someObject = new SomeClass();
OtherClass otherObject = new OtherClass();
someObject.setObject(otherObject); //"Object has changed"
otherObject.setValue(10); //nothing happens yet
I need someObject to realize that object stored inside of it changed its value to 10, but how do i do it?
(我需要someObject来实现存储在其中的对象将其值更改为10,但是我该怎么做?)
Is it even possible in OOP?(在OOP中甚至可能吗?)
ask by LostBoy translate from so