静态方法及其重写 [英] Static methods and their overriding

查看:71
本文介绍了静态方法及其重写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java不允许覆盖静态方法
但是,

Java doesn't allow overriding of static methods but,

class stat13
{
    static void show()
    {
        System.out.println("Static in base");
    }
    public static void main(String[] ar)
    {
        new next().show();
    }
}


class next extends stat13
{
    static void show()
    {
        System.out.println("Static in derived");
    }
}

这里没有重写?

推荐答案

这是隐藏,而非覆盖。要查看此内容,请将 main 方法更改为以下内容:

This is "hiding", not "overriding". To see this, change the main method to the following:

public static void main (String[] arghh) {
    next n = new next();
    n.show();
    stat13 s = n;
    s.show();
}

这应打印:

Static in derived
Static in base

如果有真正的重写,那么你会看到:

If there was real overriding going on, then you would see:

Static in derived
Static in derived

通常认为使用实例类型调用静态方法是不好的样式...就像你是做...因为很容易认为你正在调用一个实例方法,并且认为重写正在发生时会感到困惑。 Java样式检查器/代码审计工具通常会将其标记为样式错误/潜在错误。

It is generally thought to be bad style to invoke a static method using an instance type ... like you are doing ... because it is easy to think you are invoking an instance method, and get confused into thinking that overriding is happening. A Java style checker / code audit tool will typically flag this as a style error / potential bug.

这篇关于静态方法及其重写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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