Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing other class files in Java

Tags:

java

class

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.

like image 384
Jack Franklin Avatar asked Dec 05 '10 03:12

Jack Franklin


1 Answers

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
like image 166
BalusC Avatar answered Sep 27 '22 00:09

BalusC