Methods
Let's take a look at the basic anatomy of a Java class method.
We'll cover the following
Methods determine what functions an object can perform. In fact, another name for method is literally function.
Method: an abstraction
A class’s method is an abstraction for the user. The user only needs to know what a method does, not how a method does something.
For example, in a previous lesson, we discussed the Quadrilateral class. It may have a method to calculate the area. Let’s call it calculateArea
. As a programmer, you do not need to know how calculateArea
internally works. You just know that, given some parameters, this function will calculate the area for you. This is the power of abstraction! Methods are nothing but the means of creating such an abstraction.
Let’s take a look at the anatomy of a typical Java method.
Signature
The signature of a Java method conceals quite a lot of information. Given below is the signature of the main
method, which you have already seen quite a few times in this course.:
public static void main (String args[])
Let’s look at each of these keywords, one by one.
The public
keyword
The public
keyword is used to define where the method can be invoked. A public
method can be called from anywhere, e.g., from other classes. However, you can also use the private
keyword in its place, which makes the method inaccessible from any other class.
⚙️ Note: The
public
andprivate
keywords modify the access of methods and are known as access modifiers.
The static
keyword
To use most methods of a class, you need to create an object of the class first. However, we may want to access a method without creating an object first. Such methods need to have the static
keyword in their signature
The void
keyword
Next, we give the return type of our method. This keyword tells the user what data type should be expected as output when the method is called. For example, a method to calculate the area of a quadrilateral must return a double
type value. Thus, for such a method, the return type will be double
.
void
is a special return type. It means that the function does not return any value. For example, the main
function does not return anything. Thus, we label its return type as void
.
You can have primitive data types as well as reference data types as return types of a method.
main (String args[])
Next, we give our method a name. Followed by name, in parenthesis, is the list of parameters that the method takes. In the case of the main
function, we have a single parameter. We will learn what []
means in future chapters. For now, just remember that we can have parameters of any type inside []
.
Get hands-on with 1400+ tech skills courses.