Accessing other class files in Java

2019-04-10 06:32发布

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 one 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.

标签: java class
3条回答
Deceive 欺骗
2楼-- · 2019-04-10 07:04

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:

查看更多
Explosion°爆炸
3楼-- · 2019-04-10 07:08

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();
查看更多
Luminary・发光体
4楼-- · 2019-04-10 07:25

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.

查看更多
登录 后发表回答