Java Intermediate

0% completed

Previous
Next
Creating Our First Class Method

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.

Why Do We Use Methods?

  • Reusability: Methods allow you to reuse code, reducing redundancy.
  • Modularity: They help break down a program into smaller, manageable parts.
  • Readability: Using methods makes the code easier to read and maintain.
  • Encapsulation: Methods encapsulate specific logic and can control access to class data.

Syntax of a Method

Here is the general syntax for defining a method inside a class:

Image
class ClassName { // Method without parameters AccessModifier returnType methodName() { // Method body } // Method with parameters AccessModifier returnType methodName(dataType parameterName) { // Method body } }

Explanation:

  • AccessModifier: It handles how class method is accessed outside the class. We will learn about it in-detail in upcoming chapters.
  • returnType: Specifies the type of value the method will return. Use void if the method doesn't return anything.
  • methodName: The name of the method, which should be meaningful and follow camelCase convention.
  • parameterName: The name of the input variable (used only for methods with parameters). Data type must be specified.
  • Method Body: Contains the code to be executed when the method is called.

Examples

Let’s define methods for the Car and Animal classes.

1. Car Class with Methods

Java
Java
. . . .

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.

2. Animal Class with Methods

Java
Java
. . . .

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.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next