[java] Importing to several files

Started by
1 comment, last by GameDev.net 18 years, 11 months ago
I know I should know this, but it was never mentioned in my classes. What happens if I do this import java.foo.bar; in several different files? Does the Java compiler have inbuilt guards against including the same code in two different places; or perhaps an import in Java isn't really equivalent to an #include in C++? In fact, just what does an import statement do apart from making the compiler aware of where to find stuff?
To win one hundred victories in one hundred battles is not the acme of skill. To subdue the enemy without fighting is the acme of skill.
Advertisement
You can use the same import in as many files as you'd like. Think of it as being local to the particular source module:

// MyClass.javapackage mypackage;class MyClass {   public MyClass() {   }}// AnotherClass.javaimport mypackage.MyClass;class AnotherClass {   MyClass mc;}// YetAnotherClass.javaimport mypackage.MyClass;class YetAnotherClass {   MyClass mc;}// Foo.javaclass Foo {   MyClass mc;}


Even if all of the above files are part of the same project, AnotherClass and YetAnotherClass will compile just fine. Foo.java will not compile though, because MyClass is not 'visible' to it. Add an import statement and it will compile fine.
Quote:Original post by King of Men
I know I should know this, but it was never mentioned in my classes. What happens if I do this

import java.foo.bar;

in several different files? Does the Java compiler have inbuilt guards against including the same code in two


Import does not include any code at all.

You are getting confused with a completely unrelated function usually found in scripting languages or in C preprocessors that copies the contents of file X and places them here inline.

Import is purely to do with namespacing, and enables you to explicitly say "I'm using the following library, so wherever I use a class name you don't recognize, go look in that library for it, so that I don't have to bother typing out the full name of the class. Oh, and by the way, if you ever aren't sure which class I meant (because I have two libraries with the same named class in them), then give me a compiler error and tell me which ones they were so I can go back and tell you exactly which one I meant".

redmilamber

This topic is closed to new replies.

Advertisement