简体   繁体   English

Java - 错误:返回类型不兼容

[英]Java - Error : return type is incompatible

I'm learning java. 我正在学习java。 I was trying to run the code, where I got this error: return type is incompatible . 我试图运行代码,我得到这个错误: 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? 为什么会这样?

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". 我们称之为“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 : 一个好的做法是通过注释@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. 如果B扩展A然后你可以覆盖方法(比如eat ),但是你不能改变它们的签名。 So, your B class must be 所以,你的B班必须是

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

B extends A should be interpreted as B is a A. B extends A应解释为B是A.

If A's method doesn't return anything, B should do the same. 如果A的方法没有返回任何东西,B应该做同样的事情。

When a method in subclass has same name and arguments (their types, number, and order) as the method in superclass then the method in subclass overrides the one in superclass. 当子类中的方法具有与超类中的方法相同的名称和参数(它们的类型,编号和顺序)时,子类中的方法将覆盖超类中的方法。

Now for the overriding to be allowed the return type of the method in subclass must comply with that of the method in superclass. 现在,为了允许覆盖,子类中方法的返回类型必须符合超类中方法的返回类型。 This is possible only if the return type of the method in subclass is covariant with that of the method in superclass. 仅当子类中方法的返回类型与超类中的方法的返回类型协变时 ,才可能这样做。

Since, boolean </: void (read: boolean isn't subtype of void ), compiler raises the "return type incompatible" error. 因为, boolean </: void (读取: boolean不是void子类型),编译器会引发“返回类型不兼容”错误。

This is neither overloading nor overriding. 这既不是超载也不是重载。 We cannot overload on the return type and we cannot override with different different return types ( unless they are covariant returns wef Java 1.5 ). 我们不能在返回类型上重载,并且我们不能用不同的不同返回类型覆盖(除非它们是协变的返回我们Java 1.5)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM