调用超类方法而不是子类方法 [英] A superclass method is called instead of the subclass method

查看:132
本文介绍了调用超类方法而不是子类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们来看看这段代码:

Let's take a look at this code:

public class ParentClass {
    public void foo(Object o) {
        System.out.println("Parent");
    }
}

public class SubClass extends ParentClass {
    public void foo(String s) {
        System.out.println("Child");
    }

    public static void main(String args[]) {
        ParentClass p = new SubClass();
        p.foo("hello");
    }
}

我希望打印出Child,但是结果是父母。为什么java会调用超类,我该怎么做才能调用子类中的方法?

I expected this to print out "Child", but the result is "Parent". Why does java call the super class instead, and what do I do to make it call the method in the subclass?

推荐答案

SubClass#foo()不会覆盖 ParentClass#foo()因为它没有相同的形式参数。一个需要 Object ,另一个需要 String 。因此,不会应用运行时的多态,也不会导致子类方法执行。来自 Java语言规范

SubClass#foo() does not override ParentClass#foo() because it doesn't have the same formal parameters. One takes Object and the other takes a String. Therefore polymorphism at runtime is not applied and does not cause the subclass method to execute. From the Java Language Specification:


实例方法 m C 在C类中声明或继承,覆盖来自C的另一个方法 m A 在A类中声明,iff all以下是真实的:

An instance method mC declared in or inherited by class C, overrides from C another method mA declared in class A, iff all of the following are true:


  • A是C的超类。

  • A is a superclass of C.

C不会继承 m A

C does not inherit mA.

m C 的签名是 m A

...

本节定义方法签名:


两种方法或构造函数M和N具有相同的符号ature 如果它们具有相同的名称,相同的类型参数(如果有的话)(第8.4.4节),并且在将N的形式参数类型调整为M的类型参数之后,相同的形式参数类型。

Two methods or constructors, M and N, have the same signature if they have the same name, the same type parameters (if any) (§8.4.4), and, after adapting the formal parameter types of N to the the type parameters of M, the same formal parameter types.

方法的签名 m 1 是一个子签名方法的签名 m 2 如果:

The signature of a method m1 is a subsignature of the signature of a method m2 if either:


  • m 2 m 1 ,或

  • m2 has the same signature as m1, or

m1 的签名与删除(§4.6)签名 m 2

the signature of m1 is the same as the erasure (§4.6) of the signature of m2.

这篇关于调用超类方法而不是子类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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