Java - Class Methods

Hello, future Java programmers! Today, we're going to dive into the exciting world of Java class methods. Don't worry if you're new to programming – I'll guide you through this journey step by step, just like I've done for countless students over my years of teaching. So, let's roll up our sleeves and get started!

Java - Class Methods

What are Java Class Methods?

Imagine you're building a robot. The robot's body is like a class in Java, and the actions it can perform – like waving, speaking, or dancing – are like methods. Class methods are essentially the behaviors or actions that objects of a class can perform.

Why are Class Methods Important?

Class methods are the workhorses of Java programming. They allow us to:

  1. Organize our code into manageable chunks
  2. Reuse code without repeating ourselves
  3. Perform specific tasks when called upon

Creating (Declaring) Java Class Methods

Let's start by creating our first method. Here's a simple example:

public class Robot {
    public void wave() {
        System.out.println("The robot is waving!");
    }
}

In this example, we've created a class called Robot with a method called wave(). Let's break it down:

  • public: This is an access modifier. It means the method can be accessed from outside the class.
  • void: This is the return type. void means the method doesn't return any value.
  • wave(): This is the method name, followed by parentheses.
  • The code inside the curly braces {} is the method body.

Method with Parameters and Return Value

Now, let's create a more complex method:

public class Calculator {
    public int add(int a, int b) {
        return a + b;
    }
}

Here, add() is a method that:

  • Takes two parameters (int a and int b)
  • Returns an int value (the sum of a and b)

Accessing Java Class Methods

To use a method, we first need to create an object of the class (unless it's a static method, but we'll get to that later). Here's how:

public class Main {
    public static void main(String[] args) {
        Robot myRobot = new Robot();
        myRobot.wave();

        Calculator myCalc = new Calculator();
        int result = myCalc.add(5, 3);
        System.out.println("5 + 3 = " + result);
    }
}

Output:

The robot is waving!
5 + 3 = 8

We create objects (myRobot and myCalc) and then use the dot notation to call their methods.

The this Keyword in Java Class Methods

The this keyword refers to the current object instance. It's particularly useful when you have a parameter with the same name as an instance variable. For example:

public class Person {
    private String name;

    public void setName(String name) {
        this.name = name;  // 'this.name' refers to the instance variable
    }
}

Public vs. Static Class Methods

Public Methods

Public methods are instance methods. They belong to objects of the class and can access instance variables. We've already seen examples of these.

Static Methods

Static methods belong to the class itself, not to any specific instance. They can be called without creating an object. For example:

public class MathHelper {
    public static int square(int number) {
        return number * number;
    }
}

// Usage:
int result = MathHelper.square(4);  // result is 16

Static methods can't access instance variables or use the this keyword.

The finalize() Method

The finalize() method is called by the garbage collector before destroying an object. It's used for cleanup operations. However, it's generally not recommended to rely on finalize() for resource management.

public class ResourceHeavyObject {
    protected void finalize() throws Throwable {
        try {
            // Cleanup code here
            System.out.println("Object is being finalized");
        } finally {
            super.finalize();
        }
    }
}

Putting It All Together

Let's create a more complex example that showcases various aspects of class methods:

public class BankAccount {
    private String accountHolder;
    private double balance;

    public BankAccount(String accountHolder) {
        this.accountHolder = accountHolder;
        this.balance = 0.0;
    }

    public void deposit(double amount) {
        if (amount > 0) {
            this.balance += amount;
            System.out.println("Deposited: $" + amount);
        } else {
            System.out.println("Invalid deposit amount");
        }
    }

    public void withdraw(double amount) {
        if (amount > 0 && amount <= this.balance) {
            this.balance -= amount;
            System.out.println("Withdrawn: $" + amount);
        } else {
            System.out.println("Invalid withdrawal amount or insufficient funds");
        }
    }

    public double getBalance() {
        return this.balance;
    }

    public static double convertToCurrency(double amount, String currency) {
        switch (currency.toLowerCase()) {
            case "eur":
                return amount * 0.85;
            case "gbp":
                return amount * 0.74;
            default:
                return amount;
        }
    }
}

public class Main {
    public static void main(String[] args) {
        BankAccount myAccount = new BankAccount("John Doe");

        myAccount.deposit(1000);
        myAccount.withdraw(500);

        System.out.println("Current balance: $" + myAccount.getBalance());

        double balanceInEuros = BankAccount.convertToCurrency(myAccount.getBalance(), "EUR");
        System.out.println("Balance in Euros: €" + balanceInEuros);
    }
}

This example demonstrates:

  • Instance methods (deposit(), withdraw(), getBalance())
  • A static method (convertToCurrency())
  • Use of this keyword
  • Method parameters and return values

Output:

Deposited: $1000.0
Withdrawn: $500.0
Current balance: $500.0
Balance in Euros: €425.0

Conclusion

Congratulations! You've just taken a big step in your Java journey by learning about class methods. Remember, practice makes perfect. Try creating your own classes and methods, experiment with different types of methods, and don't be afraid to make mistakes – that's how we learn!

In my years of teaching, I've found that the students who excel are those who are curious and persistent. So, keep exploring, keep coding, and most importantly, have fun with it! Java is a powerful tool, and you're well on your way to mastering it.

Happy coding, future Java maestros!

Credits: Image by storyset