Creating a Class

Now we are going to create a class and call the class in the main method. As mentioned previously Java will first execute the commands inside the main methods.

First, create a class file by right clicking on the package and selecting new > class. Name your class anything that you like but something meaningful. In that class, we can create as many methods as you like. The figure below is an example that I have explained.

firstClassCreated
Class Created with a method named simpleMessage.

void – are used in the method when it is not needed to return any values.

Now, we need to call this ‘firstClassCreated’ class to the main method. First, we need to create a object for this class in the following format:

<class that wish to use> <variable name> = new  <class that you want to use>

Example:
firstClassCreated class1 = new firstClassCreated();

After creating the object for the class, we can call the method from the class now in this following format:

<classVariableName>.<methodName>();

Example:
class1.simpleMessage();

The snippet below is the Main class file that is used to call the other class.

mainClass1
Main class file that is used to call the other class

Question: Why do we need to create other class file? Why can’t we just code everything in the main method?

Yes, you can code everything in the Main method. However, if your program changes due to client requirements then it would be difficult for the programmers to make the changes. It would be difficult to make the changes because the code is too long and if the progrmmer change one thing it would affect the whole program. That is why it is good to use multiple classes to break the program down and if the program requirement changes the coder can easily make the changes without any difficulties.

Leave a comment