Error
The return type is incompatible with xyz.method
Overrides xyz.method
Overrides xyz.method
Error Type
Compile Time
Sample Code
class ParentClass{
public String method(){
System.out.println("String Method");
return "Yes";
}
}
class ChildClass extends ParentClass {
public void method(){
System.out.println("String Method");
}
}
public String method(){
System.out.println("String Method");
return "Yes";
}
}
class ChildClass extends ParentClass {
public void method(){
System.out.println("String Method");
}
}
Cause
The sub class cannot declare a method with the same name of an already existing method in the super class with a different return type. This is neither Overloading nor Overriding.
Java only allows you to alter the return type of an overridden method, as long as the new type is a subclass of the original one. This is called covariant return type.
Java only allows you to alter the return type of an overridden method, as long as the new type is a subclass of the original one. This is called covariant return type.
Resolution
If you are trying to have overloaded method, Add the method with different number or type of arguments.
class ParentClass{
public String method(){
System.out.println("String Method");
return "Yes";
}
}
class ChildClass extends ParentClass {
public void method(int x){
System.out.println("String Method");
return "No";
}
}
or If you are trying to override method, have the same return type
class ParentClass{
public String method(){
System.out.println("String Method");
return "Yes";
}
}
class ChildClass extends ParentClass {
public String method(){
System.out.println("String Method");
return "No";
}
}
class ParentClass{
public String method(){
System.out.println("String Method");
return "Yes";
}
}
class ChildClass extends ParentClass {
public void method(int x){
System.out.println("String Method");
return "No";
}
}
or If you are trying to override method, have the same return type
class ParentClass{
public String method(){
System.out.println("String Method");
return "Yes";
}
}
class ChildClass extends ParentClass {
public String method(){
System.out.println("String Method");
return "No";
}
}