We've just started learning Java for my degree and I've been given a folder with various Java classes in, each in their own .java file, with the file name the same as the name of the class it has it in.
There is o开发者_运维问答ne file which hosts a public class which has the following in:
public static void main(String[] args) {}
This creates a new instance of another class which is stored in a separate .java file, and many of the classes (each in their own .java file) seem to reference other classes without having to put anything such as
include("otherclass.php")
If you were working in PHP.
My question is: Is this how Java does things? So you can happily refer to other classes and create new instances of a class from another .java file as long as they are in the same directory?
I hope my question makes some sense!
Thanks,
Jack.
There the import
statement is for. The other class only has to be in the classpath. The classpath is basically a collection of file system paths pointing to the package root and/or individial JAR file(s). Using the import
statement is indeed not necessary when the class is in the same package as the current class (the same directory, as you say), or when you're referencing them by the full qualified name like
com.example.OtherClass otherClass = new com.example.OtherClass();
Also, the classes of the java.lang
package is always implicitly imported, you don't need to explicitly import them nor explicitly specify their path in the classpath.
See also:
- Java tutorial - Using package members
To append what what the previous gentlemen we're saying.
In java, if you have a public class file i.e. a file containing one class defined as
public class Whatever{
enter code here
}
Use can directly use it in other files by just saying
Whatever we = new Whatever();
BalusC is correct.
Java also uses an OS level environment variable called "CLASSPATH" to determine what folder(s) to look in for other .class files you may be referencing in your program. It will load classes found in the CLASSPATH as they are used with no need for an import statement. CLASSPATH almost always includes the current folder you are running the program from.
Java IDEs will usually have options for modifying CLASSPATH. You can also adjust it through whatever method your OS uses for setting environment variables.
精彩评论