In the previous topic, we explored how to define attributes (fields) in a Java class. Now, let's delve into methods, which are essential for defining the behaviors of objects. Methods allow classes to perform actions and interact with other classes or their environment.
Understanding methods is crucial because they encapsulate the functionality of a class, making your code modular, reusable, and easier to maintain.
A method in Java is a block of code that performs a specific task. It can take inputs (parameters) and return outputs. Here's the basic syntax for defining a method:
1returnType methodName(parameterList) {2// Method body3};
void.Let's create a class with a simple method that adds two numbers:
1public class Adder {2// Method to add two integers3public int add(int a, int b) {4return a + b;5}67public static void main(String[] args) {8Adder calculator = new Adder();9int result = calculator.add(5, 3);10System.out.println("The sum is: " + result);11}12}
The sum is: 8
In this example:
add that takes two integers as parameters and returns their sum.main method, we create an instance of Adder, call the add method, and print the result.To call a method, you need to use the following syntax:
1objectReference.methodName(parameterList);
Continuing from the previous example, let's call the add method multiple times:
1public class Adder {2// Method to add two integers3public int add(int a, int b) {4return a + b;5}67public static void main(String[] args) {8Adder calculator = new Adder();910int result1 = calculator.add(5, 3);11System.out.println("The sum of 5 and 3 is: " + result1);1213int result2 = calculator.add(10, 7);14System.out.println("The sum of 10 and 7 is: " + result2);15}16}
The sum of 5 and 3 is: 8 The sum of 10 and 7 is: 17
A static method belongs to the class rather than any specific instance. You can call a static method without creating an object of the class. Static methods are defined using the static keyword.
Let's modify our Adder class to include a static method:
1public class Adder {2// Static method to add two integers3public static int addStatic(int a, int b) {4return a + b;5}67public static void main(String[] args) {8// Calling the static method without creating an object9int result = Adder.addStatic(5, 3);10System.out.println("The sum is: " + result);11}12}
The sum is: 8
In this example:
addStatic that adds two integers.main method, we call addStatic using the class name Adder.Methods can have different access modifiers:
Let's define both public and private methods in a class:
1public class Calculator {2// Private method to perform multiplication3private int multiply(int a, int b) {4return a * b;5}67// Public method to perform addition8public int add(int a, int b) {9return a + b;10}1112// Public method that uses the private method13public int calculateProductAndSum(int a, int b) {14int product = multiply(a, b);15int sum = add(a, b);16return product + sum;17}1819public static void main(String[] args) {20Calculator calc = new Calculator();2122int result1 = calc.add(5, 3);23System.out.println("The sum of 5 and 3 is: " + result1);2425int result2 = calc.calculateProductAndSum(4, 6);26System.out.println("The product plus sum of 4 and 6 is: " + result2);27}28}
The sum of 5 and 3 is: 8 The product plus sum of 4 and 6 is: 32
In this example:
multiply that can only be accessed within the Calculator class.add that can be accessed from outside the class.calculateProductAndSum that uses both the private and public methods.Let's create a practical example of a BankAccount class with various methods:
1public class BankAccount {2private String accountNumber;3private double balance;45// Constructor6public BankAccount(String accountNumber, double initialBalance) {7this.accountNumber = accountNumber;8this.balance = initialBalance;9}1011// Public method to deposit money12public void deposit(double amount) {13if (amount > 0) {14balance += amount;15System.out.println("Deposited: $" + amount);16} else {17System.out.println("Invalid deposit amount.");18}19}2021// Public method to withdraw money22public boolean withdraw(double amount) {23if (amount > 0 && amount <= balance) {24balance -= amount;25System.out.println("Withdrew: $" + amount);26return true;27} else {28System.out.println("Insufficient funds or invalid withdrawal amount.");29return false;30}31}3233// Public method to get the account balance34public double getBalance() {35return balance;36}3738// Static method to display a welcome message39public static void displayWelcomeMessage() {40System.out.println("Welcome to our bank!");41}4243public static void main(String[] args) {44BankAccount.displayWelcomeMessage();4546BankAccount account = new BankAccount("123456789", 1000.0);47System.out.println("Initial balance: $" + account.getBalance());4849account.deposit(500.0);50System.out.println("Current balance: $" + account.getBalance());5152account.withdraw(200.0);53System.out.println("Current balance: $" + account.getBalance());54}55}
Welcome to our bank! Initial balance: $1000.0 Deposited: $500.0 Current balance: $1500.0 Withdrew: $200.0 Current balance: $1300.0
In this example:
BankAccount class with private attributes for the account number and balance.| Concept | Description |
|---|---|
| Method | A block of code that performs a specific task. |
| Return Type | The type of value returned by a method. Use void if the method doesn't return anything. |
| Parameter List | A list of parameters separated by commas. Each parameter has a type and a name. |
| Static Method | A method that belongs to the class rather than any specific instance. |
| Public Method | A method accessible from any other class. |
| Private Method | A method only accessible within the same class. |
In the next topic, we'll explore how to create objects using constructors and initialize their attributes. Understanding constructors is essential for creating well-defined and functional Java classes.
Stay tuned for "Java Constructors"!