Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

100
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda