Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

99
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda