Can overridden methods differ in return type?

前端 未结 12 1545
礼貌的吻别
礼貌的吻别 2020-11-22 16:11

Can overridden methods have different return types?

12条回答
  •  忘了有多久
    2020-11-22 16:50

    Overriding and Return Types, and Covariant Returns
    the subclass must define a method that matches the inherited version exactly. Or, as of Java 5, you're allowed to change the return type in the

    sample code


                                                                                                                class Alpha {
              Alpha doStuff(char c) {
                      return new Alpha();
                  }
               }
                 class Beta extends Alpha {
                        Beta doStuff(char c) { // legal override in Java 1.5
                        return new Beta();
                        }
                 } } 
    As of Java 5, this code will compile. If you were to attempt to compile this code with a 1.4 compiler will say attempting to use incompatible return type – sandeep1987 1 min ago

提交回复
热议问题