How to Use a Class from Another File in Java

In Java, you can use a class that is defined in a different file by making sure the class is accessible (usually public) and then importing it or referring to it by its fully qualified name. This lets you organize your code into separate files, reuse code across projects, and keep related classes together in packages.

What You’ll Need

  • A Java Development Kit (JDK) installed on your computer. You can check by running java -version in a terminal or command prompt.
  • A text editor or an Integrated Development Environment (IDE) such as Eclipse, IntelliJ IDEA, or Visual Studio Code.
  • Basic familiarity with compiling and running Java programs from the command line (if you’re not using an IDE).

Step-by-Step

  1. Create the class you want to use. Write a Java file, for example Helper.java, that contains a public class named Helper. The file name must match the class name, and the class should be declared public so it can be accessed from other files. For instance:
    // Helper.java
    public class Helper {
        public void greet() {
            System.out.println("Hello from Helper!");
        }
    }
  2. Place the file in the correct directory. If you’re not using packages, put both files in the same folder. If you are using packages, the directory structure must match the package declaration. For example, if Helper is in package com.example, the file must be in a folder named com/example.
  3. Write the main file that uses the class. Create another Java file, say Main.java, with a class that has a main method. Inside that method, you can create an instance of Helper and call its methods.
    // Main.java
    public class Main {
        public static void main(String[] args) {
            Helper helper = new Helper();
            helper.greet();
        }
    }
  4. Compile both files together. Open a terminal in the directory where the files are located and run javac Main.java Helper.java (or just javac *.java). This compiles both files and generates .class files.
  5. Run the program. Execute java Main (without the .class extension). You should see the output from the Helper class.
  6. If the class is in a different package, import it. At the top of Main.java, add an import statement: import com.example.Helper; (or use the wildcard import com.example.*; to import all classes in that package). Then you can use Helper as before.
  7. Alternatively, use the fully qualified name. Instead of importing, you can write com.example.Helper helper = new com.example.Helper(); in your code. This is useful when you have classes with the same name in different packages.
  8. Set the classpath if needed. If your classes are in separate directories or JAR files, you may need to specify the classpath when compiling or running. For example: javac -cp .:lib Main.java (on Windows use a semicolon instead of a colon).

Common Mistakes

  • File name doesn’t match class name. In Java, a public class must be in a file with exactly the same name (case-sensitive). If you name the file helper.java but the class is Helper, compilation will fail.
  • Forgetting to make the class public. If the class is not public, it is only accessible within the same package. If you try to use it from a different package, you’ll get an error.
  • Incorrect package declaration. If the file has a package statement, it must be the first line (except comments). The directory structure must match the package path.
  • Not compiling all files. If you only compile Main.java and not Helper.java, the compiler may not find the class. Always compile all files together or ensure the .class file exists.
  • Wrong classpath. When using packages, running java Main from the wrong directory can cause a ClassNotFoundException. Make sure you run from the root of the package structure.

Tips

  • Use an IDE. IDEs like Eclipse or IntelliJ automatically manage compilation and classpath, so you rarely need to worry about these steps manually.
  • Organize with packages. Even for small projects, using packages helps avoid naming conflicts and makes your code more modular.
  • Keep related classes together. If multiple classes are used together, consider putting them in the same package or even the same file (if they are small and only one is public).
  • Name your files descriptively. A class named Helper is vague; use names like StringUtils or DateHelper to make the purpose clear.
  • Check the import statements. If you copy code from another project, make sure the import statements match the actual package names.

Troubleshooting

Compilation error: “cannot find symbol” – This usually means the compiler can’t locate the class. Check that the file exists, the class name matches the file name, and you’ve compiled both files together. If the class is in a package, verify the package declaration and the directory structure.

Runtime error: NoClassDefFoundError – This happens when the class was available at compile time but not at runtime. Make sure the compiled .class file is in the classpath. If you’re using packages, run java from the directory that contains the top-level package folder.

Error: “class X is public, should be declared in a file named X.java” – This is a direct message that your file name doesn’t match the public class name. Rename the file to match exactly.

Import doesn’t work – Double-check the package name in the import statement. It must match the package declaration in the source file. Also, ensure that the package directory is in the classpath.

IDE shows red squiggles – In an IDE, this often means the class isn’t on the build path. Try refreshing the project, rebuilding, or checking the project structure to ensure the source folder is correctly set.

Frequently Asked Questions

Q: Can I use a class from another file without importing it?
Yes, if the class is in the same package (or in the default package), you don’t need an import. If it’s in a different package, you must either import it or use its fully qualified name.

Q: What is the default package?
If you don’t declare a package, your class belongs to the default (unnamed) package. Classes in the default package can be used by other classes in the default package without import, but they cannot be imported by classes in named packages.

Q: Can I have two public classes in the same file?
No, a Java source file can have at most one public class, and the file name must match that class. You can have multiple non-public classes in the same file, but that’s often discouraged for clarity.

Q: How do I use a class from a JAR file?
Add the JAR to your classpath. For example, when compiling: javac -cp mylib.jar Main.java, and when running: java -cp .;mylib.jar Main (on Windows) or java -cp .:mylib.jar Main (on Unix).

Q: What’s the difference between import and include?
Java doesn’t have a preprocessor like C. The import statement simply tells the compiler which classes you’re referring to by simple name. It doesn’t physically include code; it just resolves names.

Q: Why do I get a “package does not exist” error?
This usually means the package path is wrong or the classpath doesn’t include the directory containing the package. Check the package declaration in the source file and the location of the compiled classes.

In summary, using a class from another file in Java involves ensuring the class is public, placing files correctly, compiling them together, and optionally importing the class if it’s in a different package. With these steps, you can easily reuse code across your projects.