My code looks like below:
enum EnumType {
CATEGORY,
GROUP,
MAIN
}
Methods:
public void call(EnumType type){
switch(type):
case CATEGORY:
return methodForCategory();
case GROUP:
return methodForGroup();
...
}
public void methodForCategory(){
... Operations according to EnumType.CATEGORY
}
public void methodForGroup(){
... Operations according to EnumType.GROUP
}
public void methodForMain(){
... Operations according to EnumType.MAIN
}
But I want to call it without switch/case like below;
public void call(EnumType type){
methodForType(EnumType type);
}
Is it possible or is there any better alternative?
There are two ways to call a method with parameters in java: Passing parameters of primtive data type and Passing parameters of reference data type. 4. in Java, Everything is passed by value whether it is reference data type or primitive data type.
Parameters and Arguments Parameters are specified after the method name, inside the parentheses. You can add as many parameters as you want, just separate them with a comma.
In Java, two or more methods may have the same name if they differ in parameters (different number of parameters, different types of parameters, or both). These methods are called overloaded methods and this feature is called method overloading. For example: void func() { ... }
There's no concept of a passing method as a parameter in Java from scratch. However, we can achieve this by using the lambda function and method reference in Java 8.
You can create the method implementation inside the enum as below:
public enum EnumType {
CATEGORY {
@Override
public void processMethod() {
// Do something here
}
},
GROUP {
@Override
public void processMethod() {
// Do something here
}
},
MAIN {
@Override
public void processMethod() {
// Do something here
}
};
public abstract void processMethod();
}
And update call method implementation as:
public void call(EnumType type){
type.processMethod();
}
And switch code should not return anything as method return type is void
.
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