Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Can I Create method In Java With Same Type Parameter?

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?

like image 510
Sha Avatar asked Sep 14 '19 07:09

Sha


People also ask

How do you call a method with parameters from the same class in Java?

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.

How do you assign a parameter to a method in Java?

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.

How do you use the same method with different parameters?

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() { ... }

Can a method be a parameter in Java?

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.


1 Answers

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.

like image 87
Gaurav Jeswani Avatar answered Nov 14 '22 23:11

Gaurav Jeswani