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();
}
}
}
}
We can an enumeration inside a class. But, we cannot define an enum inside a method.
Enum Class in JavaAn enum class can include methods and fields just like regular classes.
Enum classes can also implement multiple interfaces like normal classes. Enum classes can also have constructors, instances variables and methods like normal Java classes.
We've learned that we can't create a subclass of an existing enum. However, an interface is extensible. Therefore, we can emulate extensible enums by implementing an interface.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With