Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a specific method based on enum type?

Tags:

java

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();
            }
        }
    }
}
like image 517
membersound Avatar asked Oct 17 '12 13:10

membersound


People also ask

Can we define method in enum?

We can an enumeration inside a class. But, we cannot define an enum inside a method.

Can we write methods in enum?

Enum Class in JavaAn enum class can include methods and fields just like regular classes.

Can enums have instance methods?

Enum classes can also implement multiple interfaces like normal classes. Enum classes can also have constructors, instances variables and methods like normal Java classes.

Can you subclass an enum?

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.


1 Answers

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();
like image 150
SLaks Avatar answered Oct 23 '22 10:10

SLaks