Methods and Parameters

Now, we are going to learn on how to call a method from another class that requires a input from the main class and pass into the method as an argument.

First, we create a class with a method that need an argument of String name. The code below shows how to create a method with an argument.

MethodNParameterSubClass
Class with a method that need an argument of String name.

This means that the method(e.g main method) which is calling this method MUST provide a String type name in order for the compiler to access the method.

NOTE: We did not declare a constructor. You may ask what is a constructor? Constructor are a special kind of method that is used to declare in class. Constructor must have the same name as the class and it does not have a return type. In this case, we do not code the Constructor out since it is a default Constructor with no argument. The compiler can automatically create the constructor as a default. For more information: Javatpoint-Constructor

In the main method, we need to create an object for the class so that it will be invoked and call the method from the class. It is same as the previous section but when you call the method in the main method you have to pass in the variable.

<class that wish to use> <variable name> = new  <class that you want to use>
<classVariableName>.<methodName>(<pass in the variable>);

Example:
firstClassCreated class1 = new firstClassCreated();
class1.simpleMessage(name);

Leave a comment