Static methods and their overriding

前端 未结 5 1750
挽巷
挽巷 2020-12-03 06:36

Java doesn\'t allow overriding of static methods but,

class stat13
{
    static void show()
    {
        System.out.println(\"Static in base\");
    }
    p         


        
5条回答
  •  长情又很酷
    2020-12-03 06:47

    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();
    }
    

    This should print:

    Static in derived
    Static in base
    

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

    Static in derived
    Static in derived
    

    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.

提交回复
热议问题