Static methods and their overriding

前端 未结 5 1717
挽巷
挽巷 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:42

    Overriding happens at the object level. for ex obj1.overridedmenthod(). and there is no concept of overriding a class level method ie... static method ex : Class.overridedmethod().

    and this concept of overriding a static method is named as method hiding.

    try out a simple example .

    0 讨论(0)
  • 2020-12-03 06:45

    Overriding happens when a child-class provides it's own implementation for a method such that the child-class instance will be invoked. The operative word here is - instance.

    Static methods are invoked in the context of the class e.g.

    stat13.show(...);
    

    OR

    next.show(...);
    

    FWIW, your sample code is not an example of overriding.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-03 06:53

    No, you're not overriding anything - you're just hiding the original method.

    It's unfortunate that Java allows you to call a static method via a reference. Your call it more simply written as:

    next.show();
    

    Importantly, this code would still call the original version in stat13:

    public static void showStat(stat13 x)
    {
        x.show();
    }
    ...
    showStat(new next());
    

    In other words, the binding to the right method is done at compile-time, and has nothing to do with the value of x - which it would normally with overriding.

    0 讨论(0)
  • 2020-12-03 06:53

    Java does not give compiler error for this. but this method will not behave like what you expect it to... better explained here

    0 讨论(0)
提交回复
热议问题