Call a specific method based on enum type?
java
Solution
You should put the method in the enum:
public enum Brand {
BMW {
@Override
public void doSomething();
},
AUDI {
@Override
public void doSomething();
};
public abstract void doSomething();
}
var.getBrand().doSomething();
Problem
Here is an abstract example of my problem: I have a general class (`Car`) which has a type (`brand`). All objects should only differ by brand, and based on this brand should be handled differently. All objects of this class are collected in a List of a Service class. The service should perform a routine on the whole list, which is mostly the same. Just one function call in between should differ. Based on this type I want to call different methods: At the moment I'm asserting equals for the enum type and call different methods based on the outcome. But this is kind of ugly and I wonder if there are better solutions on this? ``` class Car { public enum Brand { BMW, AUDI; } private Brand brand; specificMeth1(); specificMeth2(); } class Service { List<Car> bmw; List<Car> Audi; processCar() { processList(bmw); processList(audi); } processList(List<Car> list) { for (Car car : list) { if (car.getBrand.equals(Brand.BMW)) { specificMeth1(); } else { specificMeth2(); } } } } ```