Home > other >  Java method overloading based on generics restrictions
Java method overloading based on generics restrictions

Time:08-31

Simplified description: I have method process(), which should do different things for objects which implement only First interface and different things for objects which implement First and Second interface at the same time. Naturally, an object implementing both interfaces still match to the process() method which requires implementing only the First interface. But fortunately the most specific overload is called as I need.

My question is, whether it's somewhere defined that this shall work on all Java implementations.

Working sample:

public class Main
{
  public interface Printer
  {
    void print ();
  }

  public interface Calculator
  {
    void calc ();
  }

  public static class MyPrinter implements Printer
  {
    @Override public void print ()
    {
      System.out.println ("MyPrinter");
    }
  }

  public static class MyPrintingCalculator implements Printer, Calculator
  {
    @Override public void print ()
    {
      System.out.println ("MyPrintingCalculator");
    }

     @Override public void calc ()
    {
      System.out.println ("Calculating");
    }
  }

  public static <T extends Calculator & Printer > void process (T something)
  {
    something.print ();
    something.calc ();
  }

  public static void process (Printer something)
  {
    something.print ();
  }

  public static void main (String args[])
  {
    final MyPrinter printer = new MyPrinter ();
    final MyPrintingCalculator calculator = new MyPrintingCalculator ();

    process (printer);
    process (calculator);
  }
}

Try on enter image description here

starting from java 5 in 2004 , they introduced java generics and starting from java 6 in 2006 , they introduced the override in interfaces , major addition in java versions can be seen in the same window in intellij-idea like the next image :

enter image description here

so your code will work fine with any java implementation version 6 and above.

and here is image of result when running with java version 6 :

enter image description here

and the next one with java version 5:

enter image description here

and next one with java version 1.4 :

enter image description here

CodePudding user response:

Instead of a static method, you can introduce a new interface Processable that contains this method.

interface Processable<T> {
  void process(T something);
}

and then implement it with your aggregation

Processable<T> printerAndCalculator(Printer printer, Calculator calculator){
 return t -> {
  printer.print(t);
  calculator.calc(t);
 };
}
...
Processable<YourClass> printAndCalculate = printerAndCalculator(yourPrinter, yourCalculator);
printAndCalculate.process(actualParameter);

Note: I added the T argument to the print() and calc() methods because it was unused.

  • Related