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