Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

98
Views
Using ParentDecorator class for Child classes

Lets say I have four classes:

abstract class Parent {/*do stuff*/ }

class ChildA extends Parent {/*do more stuff*/}

class ChildB extends Parent {/*do more stuff differently*/}

class ParentDecorator extends Parent { 
  // do stuff
  doSomething() {
    //doing something
  }

}

How can i use ParentDecorator method doSomething() with ChildA and ChildB objects? The obvious answer would be something like:

Parent child = new ParentDecorator(child);
((ParentDecorator) child).doSomething();

but my case, all my objects are in a lists like:

ArrayList<Parent> objects; 

and i have methods like findObject(info) which returns an object from the list.

Now, lets say i want to call doStuff from the decorator for a specific object from that list. I can do something like:

Parent child1 = findObject(info);
child1 = new ParentDecorator(child1);
((ParentDecorator) child1).doSomething();

but with this, only child1 will be able to use ParentDecorator functionality, and findObject(info) will return an unchanged object. I tried this:

( (ParentDecorator) findObject(info)).doSomething();

but it throws an error "ChildA cannot be cast to ParentDecorator"

Do i need to creat ChildADecorator and ChildBDecorator, which seems a bit redundant? Or is there some workaround i cant seem to figure out?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

I realized i could simply do this:

Parent child1 = findObject(info);
child1 = new ParentDecorator(child1);
objects.remove(child1); //remove child1 from the object list
((ParentDecorator) child1).doSomething();
objects.add(child1);  //add it again

not the most elegant solution, but it will do

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!