如何从java中的其他子类通知父类有关其对象的修改?

时间:2021-07-18 16:08:18

There are classes as shown below :

课程如下所示:

class Class1 {
    //object has been created here
    Object obj=new Object();
}

class Class2 extends Class1 {}
class Class3 extends Class2 {}
...
...
// there are 99 classes like above which extends its previous parent 
class Class99 extends Class98 {
    //Here we are modifying Class1's Object obj
}

How to notify Class1 that the Object obj which belongs to your class has been modified by Class99?
Please ignore if there are some logical or compilation errors.

如何通知Class1属于您的类的Object obj是否已被Class99修改?如果存在某些逻辑错误或编译错误,请忽略。

1 个解决方案

#1


2  

You don't.

This would violate the information hiding principle. The class holding the object should provide methods to manipulate the object (not getter/setter).

这违反了信息隐藏原则。持有对象的类应该提供操作对象的方法(而不是getter / setter)。

Any other class that needs to modify the object must use one of this methods regardless if it is a descendant or not.

任何其他需要修改对象的类都必须使用其中一种方法,无论它是否是后代。


But there is an exception:

但有一个例外:

If the class (and all of its descendants) are pure data transfer objects not having any business logic then you may expose obj through getter/setter methods.

如果类(及其所有后代)是没有任何业务逻辑的纯数据传输对象,那么您可以通过getter / setter方法公开obj。

#1


2  

You don't.

This would violate the information hiding principle. The class holding the object should provide methods to manipulate the object (not getter/setter).

这违反了信息隐藏原则。持有对象的类应该提供操作对象的方法(而不是getter / setter)。

Any other class that needs to modify the object must use one of this methods regardless if it is a descendant or not.

任何其他需要修改对象的类都必须使用其中一种方法,无论它是否是后代。


But there is an exception:

但有一个例外:

If the class (and all of its descendants) are pure data transfer objects not having any business logic then you may expose obj through getter/setter methods.

如果类(及其所有后代)是没有任何业务逻辑的纯数据传输对象,那么您可以通过getter / setter方法公开obj。