Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Method Signatures and Interface

We know that method signatures include only method name and parameter lists but not method return types. So why am I getting compiler error for the following code since java does not differentiate between methods with same signature.

 public class InterfaceTest implements I2{

     public void hello(){  }

     public void world(){  }
}

interface I1{
    public int hello();
}

interface I2 extends I1{
  public void world();
}
like image 215
Shababb Karim Avatar asked Dec 09 '25 18:12

Shababb Karim


2 Answers

You have not overloading here, you are overriding and also hidding methods but not in a correct way.... there are 2 possibilities to solve your problem:

public class InterfaceTest implements I2{

    public void hello(int a){  }  // overloaded method

    @Override
    public int hello(){ return 1; }  // overriden method

    public void world(){  }   // this hides I1 method
}

Point is if you try this in a single class:

public void hello() {}
public int hello() {return 1;}

You will get Duplicate method hello() in type YourClass error, because to overloading a method you must change the FormalParameterListopt of the signature:

If two methods of a class [...] have the same name but signatures that are not override-equivalent, then the method name is said to be overloaded.

Last but not Least point:

method signatures include only method name and parameter lists but not method return types

According JSL §8.4, when you declare a method:

MethodDeclaration:
    MethodHeader MethodBody

MethodHeader:
     MethodModifiersopt TypeParametersopt Result MethodDeclarator Throwsopt

MethodDeclarator:
    Identifier ( FormalParameterListopt )

So when you do this:

  public int hellow(int number) throws Exception;
//|      |   |      |           └ throwing an exception (Throwsopt)
//|      |   |      └──────────── receiving one int argument (MethodDeclarator FormalParameterListopt )
//|      |   └─────────────────── name hellow (MethodDeclarator Identifier)
//|      └─────────────────────── returning an int (Result)
//└────────────────────────────── is a public method (MethodModifiersopt)
like image 72
Jordi Castilla Avatar answered Dec 12 '25 01:12

Jordi Castilla


You are referring method overriding here not overloading. The return type must be the same as, or a subtype, of the return type declared in the original overridden method in the superclass/interface.

like image 27
Nitesh Virani Avatar answered Dec 11 '25 23:12

Nitesh Virani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!