An array of superclass objects. How to manage them as subclasses?

Having these classes:

public abstract class Furniture public class Chair : Furniture public class Table : Furniture public class Kitchen { ArrayList <Furniture> furnitures; //other code public void function () { Furniture furniture = furnitures.get(); doSomethingInKitchen(furniture); } private void doSomethingInKitchen (Chair c); private void doSomethingInKitchen (Table t); } 

I'm looking for best practice that forces me to manipulate a Superclass furniture object as a subclass (Chair or Table).

I tried with a simple application, but when I call a function, it works with a Furniture object, not with a Table or Chair.

I tried something like:

 for each Furniture in Array List if(furniture.get() istance of Table) { currentFurniture = (Table) furniture.get(); } else if (furniture.get() istanceof Chair) { currentFurniture = (Chair) furniture.get(); } doSomethingInKitchen(currentFurniture) 

I do not know, the problem is that currentMurniture is declared as

 Furniture currentFurniture; 

And therefore, he will not be recognized by the chairman or the table, despite the casting, or if the design of the solution itself is incorrect.

+5
source share
2 answers

Your cast is lost as soon as you reassign it to a shared variable. You need to process each type separately:

 for (Furniture furniture : furnitures) { if (furniture instanceof Table) { doSomethingInKitchen((Table)furniture); } else if (furniture instanceof Chair) { doSomethingInKitchen((Chair)furniture); } } 

Ideally, however, you avoid casting altogether and implement the different logic of the subclass itself. For instance:

 abstract class Furniture { abstract void doSomethingInKitchen(); } class Table extends Furniture { @Override void doSomethingInKitchen() { // Table-specific logic } } class Chair extends Furniture { @Override void doSomethingInKitchen() { // Chair-specific logic } } 

Now in your Kitchen you just do

 for (Furniture furniture : furnitures) { furniture.doSomethingInKitchen(); } 
+3
source

since you inherit the Furniture class, there is no need to implement 2 methods for each chair and Table

 private void doSomethingInKitchen (Chair c); private void doSomethingInKitchen (Table t); 

you may have one such method

 private void doSomethingInKitchen (Furniture f); 

and you can getRid casting in forloop , and let the method cast.

 private void doSomethingInKitchen (Furniture f){ if(f instanceof Table){ //code for the table }else{ //code for the chair } } 
+2
source

All Articles