Why do we say that a static method in Java is not a virtual method?

前端 未结 5 1750
北恋
北恋 2021-01-05 06:58

In object-oriented paradigm, a virtual function or virtual method is a function or method whose behavior can be overridden within an inheriting class by a f

5条回答
  •  执笔经年
    2021-01-05 07:27

    Suppose you have class A

    public class A
    {
        public static void doAStaticThing()
        {
            System.out.println("In class A");
        }
    }
    

    And B

    public class B extends A
    {
        public static void doAStaticThing()
        {
            System.out.println("In class B");
        }
    }
    

    And a method in another class like this:

    public void foo()
    {
        B aB = new B();
        bar(B);
    }
    
    public void bar(A anA)
    {
        anA.doAStaticThing(); // gives a warning in Eclipse
    }
    

    The message you will see on the console is

    In class A
    

    The compiler has looked at the declared type of anA in method bar and statically bound to class A's implementation of doAStaticThing(). The method is not virtual.

提交回复
热议问题