Reputation: 11
I created a basic calculator program using two classes, Main and Calculator. One of my methods in the Calculator class takes in a Scanner object as its parameter. I tried to delete the Scanner import from this class but IntelliJ puts it back automatically every time. Why does this class need the Scanner import if Scanner is already imported in main?
Upvotes: 0
Views: 779
Reputation: 1113
You don't need to import anything. To use a class, it is sufficient that it can be found via your classpath, or implicitly for classes in the 'java' namespace. I view it as importing names, not importing classes (this is possibly not the way the language spec describes it).
'import' just allows you to refer to classes (etc.) by simple names, avoiding the need to type fully-qualified class names.
Here is using Scanner
without import. This is the entire program.
class n {
public static void main(String... a) {
java.util.Scanner s = new java.util.Scanner(System.in);
int n = s.nextInt();
System.out.printf(" => %d\n", n);
}
}
So, you 'import' when you need to use the class in a particular file, and don't feel like doing all the typing.
I don't use IntelliJ so cannot comment why it might fight you.
Upvotes: 1
Reputation: 3786
In Java, imports are per file, so it is expected. If you need to use a Y class in n different files (in a different package) you will need to import it in each file. Some other useful details.
package.*
to import all classes in a package.import static java.lang.Math.*;
to import static members of a class.Upvotes: 0