Can overridden methods differ in return type?

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

Can overridden methods have different return types?

12条回答
  •  名媛妹妹
    2020-11-22 16:44

    Yes, if they return a subtype. Here's an example:

    package com.sandbox;
    
    public class Sandbox {
    
        private static class Parent {
            public ParentReturnType run() {
                return new ParentReturnType();
            }
        }
    
        private static class ParentReturnType {
    
        }
    
        private static class Child extends Parent {
            @Override
            public ChildReturnType run() {
                return new ChildReturnType();
            }
        }
    
        private static class ChildReturnType extends ParentReturnType {
        }
    }
    

    This code compiles and runs.

提交回复
热议问题