Menu
Coddy logo textTech

External Files

Part of the Object Oriented Programming section of Coddy's Java journey — lesson 1 of 87.

In Java, each public class lives in its own .java file. The filename must match the class name exactly.

Create a separate file called MyClass.java

public class MyClass {
    private String name;
    
    public MyClass(String name) {
        this.name = name;
    }
    
    public String greet() {
        return "Hello, I'm " + this.name;
    }
}

Use the class in your main file

public class Main {
    public static void main(String[] args) {
        MyClass obj = new MyClass("Alice");
        System.out.println(obj.greet());
    }
}

Output:

Hello, I'm Alice

Classes in the same package (folder) can access each other directly. For classes in different packages, you use import statements.

challenge icon

Challenge

Easy

You are given Java files (MyClass.java and Main.java). Create a MyClass object in Main.java to use the class from the external file.

Cheat sheet

In Java, each public class must be in its own .java file with a matching filename.

Example class in MyClass.java:

public class MyClass {
    private String name;
    
    public MyClass(String name) {
        this.name = name;
    }
    
    public String greet() {
        return "Hello, I'm " + this.name;
    }
}

Using the class in Main.java:

public class Main {
    public static void main(String[] args) {
        MyClass obj = new MyClass("Alice");
        System.out.println(obj.greet());
    }
}

Classes in the same package can access each other directly. For classes in different packages, use import statements.

Try it yourself

import java.util.Scanner;
// TODO: No extra import needed if files are in the same package

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String testCase = scanner.nextLine();
        
        // TODO: Create a MyClass object
        
        System.out.println("Test completed");
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming