Lesson 30: Methods

Methods are one of the fundamentals of programming.  As you might recall from our object-oriented programming lesson, we talked about how classes are typically nouns and methods are verbs.  They help reduce redundancy by being able to use them an unlimited amount of times throughout our code for different instances.

Thus far, we have been putting most of our action-taking code within a class and main method.  However, as our programs start to become more complex, it will be important to split our code into different methods, classes, and objects to make troubleshooting easier.  Now let’s look at a method in action.

In the example above, we have two separate methods.  The first one listed is a user created method, and the second one is our main method.  

In future lessons, we will cover the keywords static and void.  For now,  just know that static means that the data is associated only within its class, but not any created instances of it.

The keyword void means that we do not want a return value.  For example, if we wanted a String returned, then the method would look like static String methodName(){

After the first two keywords(static and void), we see printingMethod(){ }.  The method name is assigned by the programmer.  It is then followed by parentheses and a set of brackets.

What we put in the brackets, is what will be executed whenever we call the method.  In the example above, we have a print statement.  

To call the method in this example, all we must do is type our method’s name and parentheses in our main method.

If we do not call printingMethod() in the main method, it will not print.  Also, if we call the method twice, it will perform its function twice by printing the sentence twice. 

Also, you can add the method before or after the main method and it will work regardless.  

Methods are an essential component to object-oriented programming and we will continue to see and use them in future lessons.

GitHub link.

Leave a Reply

%d bloggers like this: