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

前端 未结 5 980
佛祖请我去吃肉
佛祖请我去吃肉 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:01

    Good question !!

    I think the result is the difference between how java compiler handles expressions vs statements.

    Date d = new Date(); // a statement
    

    where as

    new Thing().getDate().getTime()
    

    is an expression as it occurs inside println method call. When you call getDate on new Thing() the compiler tries to handle the expression by looking at the type info for Thing class, which is where it gets the declaration of type Date. But when you try to use Date separately in a statement like

    Date d = new Thing().getDate();
    

    you are assigning the result to a type in the current scope (class TestUsesThing ), compiler tries to resolve the type within that scope. As a result, you see the compiler error for unknown type.

提交回复
热议问题