Get startedGet started for free

Class methods

1. Class methods

Methods are the second key component that classes contain in OOP. A good way to think of methods is as an action or operation that a class defines to enable objects from the class to perform.

2. Example of car properties

If you use a real-world example of a car, we know that a car can have properties like color and model, which are pieces of information that describe it. However, a car also has a set of actions that it can perform. These actions can be simple, like turning on or off, or more complex, like driving. The operations of a car can also sometimes obtain and return data to us; for example, when connecting our phone to our car's Bluet

3. Types of methods

There are two ways to classify methods based on their operations in Java. The first classification is for methods that perform some action but do not return any data to us in our code. These methods are called void methods. The second type of method is methods that explicitly return information, and these are called non-void methods.

4. Void methods

Let's see an example of a void method. If we had a Car class, we could create a new honkHorn() method and mark it as void. Inside this method, we print the message "beep beep." If we create an instance of our Car method called myNewCar and call the honkHorn() method, we will see the message "beep beep" printed out on the console. The honkHorn() method doesn't return any data; it only performs an action that prints out a message.

5. Creating non void methods

Now, let's look at a method with a return type. Let's consider a class called Formula, a helper class that contains multiple formulas for everyday mathematical calculations so we don't have to rewrite our code

6. Let's practice!

Methods are a central feature in Java, allowing us to compose more reusable code. Now it's your turn to create some void and non-void methods in your classes.