0% completed
A method in Java is a block of code that performs a specific task. Methods define the behavior of objects and are essential for executing logic inside a class. They can take parameters, return values, or simply perform an action.
In this lesson, we’ll learn how to define methods inside a class and understand their structure through examples. We will focus on methods with and without parameters.
Here is the general syntax for defining a method inside a class:
class ClassName { // Method without parameters AccessModifier returnType methodName() { // Method body } // Method with parameters AccessModifier returnType methodName(dataType parameterName) { // Method body } }
Explanation:
void
if the method doesn't return anything.Let’s define methods for the Car
and Animal
classes.
Explanation:
startEngine
: A method without parameters that simply prints "Engine started."setSpeed
: A method with a single parameter, speed
, which specifies the car's speed.Explanation:
makeSound
: A method without parameters that prints "Animal is making a sound."eat
: A method with a single parameter, food
, which specifies what the animal is eating.Methods in a class define the behavior of objects. They can be created with or without parameters, depending on the functionality required. In this lesson, we defined simple methods in the Car
and Animal
classes, including examples with and without parameters.
.....
.....
.....