Java返回值需要注意的地方

1. 在方法重写时不能变更声明的返回类型,但可以为声明的返回类型的子类


   
   
  1. public class Foo{
  2. void go() { }
  3. }
  4. class Bar extends Foo {
  5. String go() { // 不合法
  6. return ;
  7. }
  8. }

该段代码会报如下错误


   
   
  1. Multiple markers at this line
  2. - overrides Foo.go
  3. - The return type is incompatible with
  4. Foo.go()

但是如果在继承的同时还进行了重载,则声明的返回类型可以改变,如下代码能正常运行:


   
   
  1. public class Foo{
  2. void go() { }
  3. }
  4. class Bar extends Foo {
  5. String go(int x) {
  6. return ;
  7. }
  8. }

重写的方法声明的返回类型可以为父类方法的子类:


   
   
  1. public class Foo{
  2. Foo go(){
  3. return new Foo();
  4. }
  5. }
  6. class Bar extends Foo {
  7. Bar go() {
  8. return new Bar();
  9. }
  10. }


2. 如果声明的返回类型为一个对象,则return返回的类型可以为null:


   
   
  1. public class Foo{
  2. Foo go() {
  3. return ;
  4. }
  5. }

3. return的类型可以为声明的返回类型的子类:


   
   
  1. class Bar extends Foo {
  2. Foo go() {
  3. return new Bar();
  4. }
  5. }

4. 当声明的返回类型为抽象类或者接口时,return的类型可以为继承该抽象类或者实现该接口的类:


   
   
  1. abstract class Foo{
  2. abstract Foo go();
  3. }
  4. class Bar extends Foo {
  5. Foo go() {
  6. return new Bar();
  7. }
  8. }


   
   
  1. interface runnable{
  2. runnable go();
  3. }
  4. class Bar implements runnable {
  5. public runnable go() {
  6. return new Bar();
  7. }
  8. }

5. 当声明的发挥类型为void时,可以return但是不能return任何值,也不能return null,


   
   
  1. abstract class Foo{
  2. abstract void go();
  3. }
  4. class Bar extends Foo {
  5. public void go() {
  6. return;
  7. }
  8. }



            </div>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值