0

I am facing an issue in context of IBM's WSDL2Java but let me describe with simple example.

Class Stub {
    void printValue(String val){
       System.out.println(val);
    }
}

Interface Printer {
    boolean printValue(String val) throws Exception;
} 

Class myPrinter extends Stub implements Printer{
    boolean printValue(String val) throws Exception{
    //Implementation here
    }
} 

myPrinter class will not compile now because of incompatible return type error. This is because compiler gives priority to parent class method which is fine and logical. But I would like suggestions on how can I make myPrinter class valid without touching Stub class and Printer interface and at the same time implement the printValue from interface in my class.

  • You simply cannot combine `Stub` and `Printer` in that situation. `Class` should be lowercase, `Interface` should be lowercase, `myPrinter` should be `MyPrinter`. – luk2302 Mar 09 '18 at 11:08
  • I have typed it on my cellphone. Please ignore the syntax. – Rishi Parmar Mar 09 '18 at 11:14

2 Answers2

1

Something has to give: a single class cannot have two methods with the same name and parameter types, but different return types. This includes methods acquired through inheritance.

To make this compile you could do one of the following things:

  • Rename the method in Stub or Printer - this is the most logical approach when you have access either to the class or to the interface,
  • Replace inheritance with composition - rather than inheriting MyPrinter from Stub, give MyPrinter a member of type Stub, and implement Printer interface,
  • Wrap Stub in a class with renamed method - you could write StubWrapper class which exposes the same methods as Stub, but with the signature of printValue changed not to conflict with that in the Printer interface. Now MyPrinter can inherit it.
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

I'm afraid you can't. Methods in Java are identified by their signature. The signature consists of the method name and the types of the parameters. The return type doesn't belong to the signature, meaning the compiler can't distuingih the two inherrited operations.

André Stannek
  • 7,773
  • 31
  • 52