Writing a Method

public void square()
  • ”public” starts the method so it can be used outside of the class
  • ”void” is the return type, which specifies the value returned before a method completes its execution and exits
  • ”square()” is the name of the method followed by parentheses. The parentheses are either empty because there are no parameters or contain the parameters for the method. It is the method signature, which consists of a name and parameter list.

When we call a method, Java looks for the method in the class to find its instructions.

When we say return, this refers to exiting a method and going back to the point in the program that called it with requested value or information.

When the return type is void, this means that the method shouldn’t have a return value. The method performs its intended task but doesn’t give a value back to where the method was called.

A subclass can access methods in the superclass, but a superclass can’t access methods in the subclass.

How to Write a Method in a Class

Step 1: Make sure you are inside the curly braces ({}) for the class.

Step 2: Write public, the return type, and the method signature.

Step 3: Write the code that the method should execute.

Since a class is a blueprint for an object, we don’t refer to a specific object when calling methods in the current class or a superclass.