I'm learning java. I was trying to run the code, where I got this error: return type is incompatible
.
Part of code where it showed me error.
class A {
public void eat() { }
}
class B extends A {
public boolean eat() { }
}
Why it is happening?
Swapping the inappropriate constructor call with an instance of the correct type solves the issue, as shown in Fig. 6(b). Fig. 6 also serves as an example to show how the incompatible types error is, in fact, a generalization of the method X in class Y cannot be applied to given types error explored in [4].
Returning a Value from a Method If a method does not return a value, it must be declared to return void . However, the pop() method in the Stack class returns a reference data type: an object. Methods use the return operator to return a value. Any method that is not declared void must contain a return statement.
In order to solve the missing return statement error, we simply need to add the return statement to the method just like to the one we did in case one. So, we will return the some value of the same type which we used before the name like as: public static String checkNumber( int number) {
From Java 5 onwards, we can override a method by changing its return type only by abiding the condition that return type is a subclass of that of overridden method return type.
This is because we cannot have two methods in classes that has the same name but different return types.
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.
However, the subclass can declare a method with the same signature as in super class. We call this "Overriding".
You need to have this,
class A {
public void eat() { }
}
class B extends A {
public void eat() { }
}
OR
class A {
public boolean eat() {
// return something...
}
}
class B extends A {
public boolean eat() {
// return something...
}
}
A good practice is marking overwritten methods by annotation @Override
:
class A {
public void eat() { }
}
class B extends A {
@Override
public void eat() { }
}
if B
extends A
then you can override methods (like eat
), but you can't change their signatures. So, your B
class must be
class B extends A {
public void eat() { }
}
B extends A
should be interpreted as B is a A.
If A's method doesn't return anything, B should do the same.
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