Why is import of class not needed when calling method on instance (Java)

前端 未结 5 975
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-17 15:37

Something that\'s confused me - an example:

Thing.java:

import java.util.Date; 

class Thing { 
    static Date getDate() {return new Date();}
}
         


        
5条回答
  •  天命终不由人
    2020-12-17 16:10

    import statements are used for couple of things.

    1. Compiler type checking and avoid naming collision.
    2. Ensures byte code linkage

    Whenever we say

    System.out.println( new Thing().getDate().getTime() )
    

    The compiler parses this statement left to right and gets into that class.

    First level compiler parsing.

    1. Go to thing class
    2. compile doesn't have any linkage or ClassVersion error from Thing.class

    3. Check Thing.class has getDate method.
    4. if #3 is good then compiler pointer is still in Thing.class (which has date import statements) and I could invoke Time method.
    5. As a consumer TestUsesThing gets only long variable.

      System.out.println( new Thing().getDate() )
      

      5.1 In this case we are implicitly accessing .toString() method

提交回复
热议问题