为什么子类已经覆盖了父类的静态方法呢? [英] Why static method of parent class is called when subclass has already overridden it?

查看:75
本文介绍了为什么子类已经覆盖了父类的静态方法呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当静态方法在子类中被重写时,我对它的行为感到困惑.

I am confused by the behaviour of the static method when it is overridden in the subclass.

下面是代码:

public class SuperClass {

    public static void staticMethod() {
        System.out.println("SuperClass: inside staticMethod");
    }
}

public class SubClass extends SuperClass {

//overriding the static method
    public static void staticMethod() {
        System.out.println("SubClass: inside staticMethod");
    }
}


public class CheckClass {

    public static void main(String[] args) {

        SuperClass superClassWithSuperCons = new SuperClass();
        SuperClass superClassWithSubCons = new SubClass();
        SubClass subClassWithSubCons = new SubClass();

        superClassWithSuperCons.staticMethod();
        superClassWithSubCons.staticMethod();
        subClassWithSubCons.staticMethod();

    }
}


Below is the output which we are getting :

    1) SuperClass: inside staticMethod
    2) SuperClass: inside staticMethod
    3) SubClass: inside staticMethod

为什么在第二种情况下在这里调用超类的静态方法?

Why static method of superclass gets called here in the second case?

如果方法不是静态的,则根据多态性,当在运行时传递子类对象时,将调用子类的方法.

If method is not static, then according to polymorphism, method of the subclass is called when subclass object is passed on runtime.

推荐答案

静态方法解析始终基于Reference类型.
代码

static method resolution is always based on the Reference type.
The code

superClassWithSuperCons.staticMethod();
superClassWithSubCons.staticMethod();
subClassWithSubCons.staticMethod();

在编译后会转换为此

SuperClass.staticMethod();
SuperClass.staticMethod();
SubClass.staticMethod();

因此,它是对SuperClass方法的调用,而不是对子类方法的调用.因此,您将获得SuperClass方法的输出.

Accroding to this it is the call to SuperClass method not the subclass method.So you are getting the output of SuperClass method.

这篇关于为什么子类已经覆盖了父类的静态方法呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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