Swathi Rajanna
Swathi Rajanna

Reputation: 11

How to notify the parent class about its object modification from other child class in java?

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.

Upvotes: 1

Views: 145

Answers (1)

Timothy Truckle
Timothy Truckle

Reputation: 15622

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).

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.

Upvotes: 2

Related Questions