Java: Adding a class in a separate file

This entry is part 43 of 54 in the series Learn Java

When we first create a class using Netbeans, it will generate a template similar to below.

package music;

public class Music {

    public static void main(String[] args) {

    }  
}

Say we are working on a very large project and we would like to create a different class and put the class in a different file making it easier for us to manage the project.

To add, you can right click on the music folder as shown in the screenshot below.

add

Right click on music and from the menu, click on New -> Java Class.

add_rock_class

A Rock.Java file will be created for us.

In the main Music.java, type in the following code.

package music;

public class Music {

    public static void main(String[] args) {

        Rock r = new Rock();
    }  
}

In the Rock.java file, type in the following code.

package music;

public class Rock {

    public Rock() {
        System.out.println("The Rock Class In A Different File");
    }
}

After compiling and running it, the output will be as below.

class_output

Series Navigation<< Java: Constructing a subclass
Java: Overriding superclass method >>