Java - 错误:返回类型不兼容 [英] Java - Error : return type is incompatible

查看:2076
本文介绍了Java - 错误:返回类型不兼容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习java。我试图运行代码,我收到此错误:返回类型不兼容
显示错误的部分代码。

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() { }
}

为什么会这样?

推荐答案

这是因为我们不能拥有类中具有相同名称但返回类型不同的两种方法。

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.

但是,子类可以声明一个方法,其签名与超类中的签名相同。
我们称之为Overriding。

However, the subclass can declare a method with the same signature as in super class. We call this "Overriding".

你需要这个,

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...
    }
}

一个好的做法是通过注释标记覆盖的方法 @Override

A good practice is marking overwritten methods by annotation @Override:

class A {
    public void eat() { }
}

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

这篇关于Java - 错误:返回类型不兼容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆