Do I need to import a package only to create an object or call a method from this object?

class TestFormat { public static void main(String[] args) { System.out.println("hello"); } } 

In the simple code above, the out object is of type java.io.PrintStream . The println() method also belongs to the PrintStream class. PrintStream is in another package, then java.lang , which is the standard java package.

My question is: how can we use a class method from a package ( java.io ) that we did not even import? It is provided that an object of this class has already been provided to us, but does this mean that we need to import the package only to create an object of the class from this package and not use its methods later?

Thnax in advance!

+4
source share
2 answers

You misunderstand what imports do.

Yes, you can use a class and its methods without an import statement. This means that you will need to enter java.io.PrintStream instead of the short name PrintStream .

the class loader looks for the class path for the .class file when using the class for the first time; import has nothing to do with this process. This is just a way to save you the trouble of entering a fully qualified class name.

You can write Java successfully and never use import if you want. You just need to be a machine with a good touch.

+7
source

import just saves you from entering the full path if you import this class that you can write PrintStream, otherwise you need to write the full path java.io.PrintStream

0
source

All Articles