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?
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).
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With