Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

java 重写时返回类型疑惑 #848

Open
Zouxxyy opened this issue Jul 8, 2020 · 3 comments
Open

java 重写时返回类型疑惑 #848

Zouxxyy opened this issue Jul 8, 2020 · 3 comments

Comments

@Zouxxyy
Copy link

@Zouxxyy Zouxxyy commented Jul 8, 2020

Java基础知识 1.4.3.2.重写 中指出重写时返回值类型相同;我觉得应改为返回类型小于等于父类方法返回类型。

我注意到 issue#723 改正了这一说法,能说说原因吗?感谢!

下面是我在JDK 1.8进行的测试

public class A {

    public Number fun() {
        System.out.println("A");
        return null;
    }
}

class B extends A {

    @Override
    public Integer fun() {
        System.out.println("B");
        return null;
    }

    public static void main(String[] args) {
        A a = new B();
        a.fun();
    }
}

// 输出 B
@wangpeipei90
Copy link

@wangpeipei90 wangpeipei90 commented Jul 8, 2020

你的例子应该是正确的。
Returns type can be different only if the parent class method return type is
a supertype of child class method return type.
See StackOverflow post:

@Rorke76753
Copy link

@Rorke76753 Rorke76753 commented Jul 24, 2020

为什么我用跟你相同的代码测试结果不一样呢,我也是jdk8但输出的是子类的内容

public class ChildrenClass extends SuperClass{
    @Override
    public Integer test() {
        System.out.println("int");
        return null;
    }

    public static void main(String[] args) {
        SuperClass clazz = new ChildrenClass();
        clazz.test();
    }
}

class SuperClass {
    public Number test(){
        System.out.println("number");
        return null;
    }
}

每次输出的都是int

@Zouxxyy Zouxxyy closed this Jul 24, 2020
@Zouxxyy
Copy link
Author

@Zouxxyy Zouxxyy commented Jul 24, 2020

为什么我用跟你相同的代码测试结果不一样呢,我也是jdk8但输出的是子类的内容

public class ChildrenClass extends SuperClass{
    @Override
    public Integer test() {
        System.out.println("int");
        return null;
    }

    public static void main(String[] args) {
        SuperClass clazz = new ChildrenClass();
        clazz.test();
    }
}

class SuperClass {
    public Number test(){
        System.out.println("number");
        return null;
    }
}

每次输出的都是int

是的,就是输出子类的,表示重写成功, 我当时好像忘记改了,我怎么会写aaa。。。

@Zouxxyy Zouxxyy reopened this Jul 24, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Linked pull requests

Successfully merging a pull request may close this issue.

None yet
3 participants
You can’t perform that action at this time.