Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Something that's confused me - an example:

Thing.java:

import java.util.Date; 

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

(same package) TestUsesThing.java:

// not importing Date here.

public class TestUsesThing {

    public static void main(String[] args) {
        System.out.println(Thing.getDate().getTime()); // okay
        // Date date = new Date(); // naturally this wouldn't be okay
    }

}

Why is it not necessary to import Date to be able to call getTime() on one of them?

like image 445
jjujuma Avatar asked Apr 24 '09 13:04

jjujuma


People also ask

Do you have to import classes in Java?

In Java, you do not need to add import statements for classes that exist within the same package (they are actually automatically “imported” by the compiler).

Why we dont need to import string in Java?

The String class belongs to the java.This is the default package of the Java language therefore it is not mandatory to import it to use its classes.

What does importing a class do in Java?

import is a Java keyword. It declares a Java class to use in the code below the import statement. Once a Java class is declared, then the class name can be used in the code without specifying the package the class belongs to. Use the '*' character to declare all the classes belonging to the package.


1 Answers

Importing in Java is only necessary so the compiler knows what a Date is if you type

Date date = new Date();

Importing is not like #include in C/C++; all types on the classpath are available, but you import them just to keep from having to write the fully qualified name. And in this case, it's unnecessary.

like image 65
Michael Myers Avatar answered Sep 21 '22 14:09

Michael Myers