Why do these two code samples produce different outputs?

后端 未结 5 985
离开以前
离开以前 2021-01-18 02:57

Sample 1:

 class Animal {
     public static void saySomething() { System.out.print(\" Gurrr!\"); 
   }
 }
 class Cow extends Animal {
    public static void         


        
5条回答
  •  悲哀的现实
    2021-01-18 03:11

    When you call saySomething() on an animal, the actual type of the animal doesn't count because saySomething() is static.

    Animal cow = new Cow();
    cow.saySomething(); 
    

    is the same as

    Animal.saySomething();
    

    A JLS example :

    When a target reference is computed and then discarded because the invocation mode is static, the reference is not examined to see whether it is null:

    class Test {
      static void mountain() {
          System.out.println("Monadnock");
      }
      static Test favorite(){
           System.out.print("Mount ");
           return null;
       }
       public static void main(String[] args) {
           favorite().mountain();
       }
    

    }

    which prints:
    Mount Monadnock
    Here favorite returns null, yet no NullPointerException is thrown.


    Resources :

    • JLS - Is the Chosen Method Appropriate?

    On the same topic :

    • Java Static confusion

提交回复
热议问题