Java - Error: return type incompatible

I am learning java. I tried to run the code where I received this error. he says the return type is incompatible. The part of the code where he showed me the error

  class A {
            public void eat() { }
     }

     class B extends A {
            public boolean eat() { }
     }

Why is this happening?

+3
source share
5 answers

This is because we cannot have two methods in classes with the same name, but with different types of returned data.

A subclass cannot declare a method with the same name as an existing method in a superclass with a different return type.

However, a subclass can declare a method with the same signature as the superclass. We call it "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...
    }
}

It is good practice to mark overwritten methods with annotations @Override:

class A {
    public void eat() { }
}

class B extends A {
    @Override
    public void eat() { }
}
+8

if B extends A, (, eat), . , B

 class B extends A {
        public void eat() { }
 }
+2

B extends A B - A.

, B .

+2

( , ) , .

, , . , .

boolean </: void (read: boolean void), " ".

+2

. , ( , Java 1.5).

0

All Articles