Java Methods and Basic Object-Oriented Programming

JavaJavaBeginner
Practice Now

Introduction

In this lab, we'll take your Java skills to the next level by introducing you to methods and the basics of object-oriented programming (OOP). These concepts are fundamental to writing more organized, reusable, and efficient code. We'll cover:

  1. Creating and using methods to organize code and promote reusability
  2. Understanding the basics of classes and objects
  3. Implementing a simple class with methods and attributes

By the end of this lab, you'll be able to write Java programs that use methods to break down complex problems into smaller, manageable pieces. You'll also gain an understanding of how object-oriented programming works in Java, which is crucial for building larger, more complex applications. Don't worry if these concepts sound complicated – we'll take it step by step, and by the end, you'll see how these ideas make your code more organized and powerful.

Let's dive in!

Understanding and Creating Methods

Methods are like mini-programs within your main program. They help you organize your code, make it more readable, and allow you to reuse code without repeating yourself. Think of methods as specialized tools in a toolbox – each one designed for a specific task.

  1. Let's start by opening the MethodDemo.java file in the WebIDE. You'll see this starter code:

    public class MethodDemo {
        public static void main(String[] args) {
            System.out.println("Welcome to the Method Demo!");
    
            // TODO: Call methods here
        }
    
        // TODO: Add methods here
    }

    This is the basic structure of our Java program. The main method is where our program starts executing.

  2. Now, let's create our first method. We'll make a simple method that prints a greeting. Add this method outside and after the main method, at the class level:

    public class MethodDemo {
        public static void main(String[] args) {
            System.out.println("Welcome to the Method Demo!");
    
            // TODO: Call methods here
        }
    
        // Add the new method here, outside and after the main method
        public static void printGreeting(String name) {
            System.out.println("Hello, " + name + "! Welcome to Java methods.");
        }
    }

    Let's break this down:

    • public: This keyword means the method can be accessed from anywhere in our program.
    • static: This means the method belongs to the class itself, not to any specific instance of the class. Don't worry too much about this for now; we'll explore it more later.
    • void: This indicates that our method doesn't return any value. It just performs an action (printing a greeting).
    • printGreeting: This is the name we've given our method. We can call it using this name.
    • (String name): This is the parameter our method accepts - a String called name. When we call this method, we'll need to provide a name.
  3. Great! Now that we've created a method, let's use it. In the main method, replace the TODO comment with:

    printGreeting("Alice");
    alt text

    This line calls our printGreeting method and passes it the name "Alice".

  4. Save the file, then let's compile and run the program. In the terminal at the bottom of your WebIDE, type these commands:

    javac ~/project/MethodDemo.java
    java -cp ~/project MethodDemo

    The first command compiles our Java file, and the second runs it. You should see output like this:

    Welcome to the Method Demo!
    Hello, Alice! Welcome to Java methods.
  5. Excellent! You've just created and used your first Java method. Let's call it again with a different name. Add this line in the main method, right after the first printGreeting call:

    printGreeting("Bob");
  6. Save, compile, and run the program again. You should now see:

    Welcome to the Method Demo!
    Hello, Alice! Welcome to Java methods.
    Hello, Bob! Welcome to Java methods.

    See how we can reuse our method with different inputs? This is one of the big advantages of using methods.

  7. Now, let's create a method that returns a value. Add this method to your class, below the printGreeting method:

    public static int sumNumbers(int a, int b) {
        return a + b;
    }

    This method takes two integers, adds them, and returns the result. Notice that instead of void, we use int to indicate that this method returns an integer.

  8. Let's use this new method in our main method. Add these lines at the end of the main method:

    int result = sumNumbers(5, 7);
    System.out.println("The sum of 5 and 7 is: " + result);

    Here, we're calling our sumNumbers method with the values 5 and 7, and storing the result in a variable called result. Then we're printing that result.

  9. Save, compile, and run the program again. You should see the additional output:

    The sum of 5 and 7 is: 12
    alt text

Congratulations! You've created and used your first Java methods. You've seen how methods can perform actions (like printing greetings) and return values (like the sum of two numbers). Methods allow you to break your code into smaller, reusable pieces, making your programs easier to understand and maintain.

Introduction to Classes and Objects

Now that we understand methods, let's take a step into object-oriented programming by creating a simple class. In object-oriented programming, we use classes as blueprints to create objects. Think of a class like a cookie cutter, and objects as the cookies you make with it.

  1. Open Car.java and let's start building our class. First, we'll define the class and add some attributes:

    public class Car {
        // Attributes
        private String make;
        private String model;
        private int year;
    }

    These attributes (also called fields or properties) define what every Car object will have. Every car will have a make, a model, and a year of manufacture.

    The private keyword means these attributes can only be accessed within the class. This is a concept called encapsulation, which helps protect the data within our objects.

  2. Now, let's add a constructor to our class. A constructor is a special method that's called when we create a new object. It's used to initialize the object's attributes. Add this constructor to your Car class:

    // Constructor
    public Car(String make, String model, int year) {
        this.make = make;
        this.model = model;
        this.year = year;
    }

    This constructor takes three parameters and uses them to set the values of our attributes. The this keyword is used to refer to the current object's attributes.

  3. Next, let's add a method to our class that will display information about the car. Add this method to your Car class:

    // Method
    public void displayInfo() {
        System.out.println("Car Information:");
        System.out.println("Make: " + make);
        System.out.println("Model: " + model);
        System.out.println("Year: " + year);
    }
    alt text

    This method doesn't take any parameters or return any value. It simply prints out the car's information.

  4. Great! We've created our Car class. Now let's open CarDemo.java and add the following code:

    public class CarDemo {
        public static void main(String[] args) {
            // We'll add code here in the next step
        }
    }

    This sets up the basic structure for our demo program.

  5. Now, let's create some Car objects and use them. Add this code inside the main method:

    Car myCar = new Car("Toyota", "Corolla", 2022);
    myCar.displayInfo();
    
    Car friendsCar = new Car("Honda", "Civic", 2023);
    friendsCar.displayInfo();

    Here, we're creating two Car objects. The new keyword is used to create a new object, and we're calling the constructor we defined earlier to set the make, model, and year. Then we're calling the displayInfo method on each car.

  6. Before we compile and run our program, it's important to note that we're working with multiple Java files (Car.java and CarDemo.java). When compiling multiple files that have dependencies, we need to compile them together. Also, make sure that CarDemo.java is in the same directory as Car.java, or you'll need to import the Car class at the beginning of CarDemo.java.

    If CarDemo.java and Car.java are in different directories, you might need to add an import statement at the top of CarDemo.java:

    import packagename.Car;  // Replace 'packagename' with the actual package name if applicable

    Now, let's compile and run the CarDemo program:

    javac ~/project/Car.java ~/project/CarDemo.java
    java -cp ~/project CarDemo

    The first command compiles both our Java files together, ensuring that all dependencies are resolved. The second command runs our CarDemo class.

    You should see output like this:

    Car Information:
    Make: Toyota
    Model: Corolla
    Year: 2022
    Car Information:
    Make: Honda
    Model: Civic
    Year: 2023
    alt text

Congratulations! You've just created your first Java class and used it to create objects. This is the foundation of object-oriented programming in Java. You've defined a blueprint (the Car class) and used it to create specific instances (the Car objects). Each object has its own set of attributes, but they all share the same structure and behavior defined by the class.

Enhancing Our Class with More Methods

Now that we have a basic understanding of classes and objects, let's enhance our Car class with more methods to make it more useful. We'll add methods that represent actions a car can perform and properties we might want to know about a car.

  1. Open the Car.java file. Let's add a method that represents the car accelerating. Add this method to the Car class:

    public void accelerate() {
        System.out.println("The " + make + " " + model + " is accelerating.");
    }

    This method doesn't change any of the car's attributes, it just prints a message about the car accelerating.

  2. Now, let's add a method for braking. Add this method to the Car class:

    public void brake() {
        System.out.println("The " + make + " " + model + " is braking.");
    }

    Again, this method just prints a message about the car's action.

  3. Next, let's add a method that returns information about the car. Add this method:

    public String getMakeAndModel() {
        return make + " " + model;
    }

    This method combines the make and model into a single string and returns it. Notice that the return type is String, not void, because this method is giving us back some information.

  4. Finally, let's add a method that determines if a car is considered an antique. In many places, a car is considered an antique if it's over 25 years old. Add this method:

    public boolean isAntique() {
        int currentYear = java.time.Year.now().getValue();
        return (currentYear - year) > 25;
    }

    This method uses Java's built-in Year class to get the current year. It then calculates the age of the car and returns true if it's over 25 years old, false otherwise.

  5. Now that we've added these methods to our Car class, let's update our CarDemo.java file to use them. Open CarDemo.java and replace its contents with:

    public class CarDemo {
        public static void main(String[] args) {
            Car myCar = new Car("Toyota", "Corolla", 2022);
            Car classicCar = new Car("Ford", "Mustang", 1965);
    
            myCar.displayInfo();
            myCar.accelerate();
            myCar.brake();
    
            System.out.println(classicCar.getMakeAndModel() + " is an antique: " + classicCar.isAntique());
    
            Car[] carArray = {myCar, classicCar};
            for (Car car : carArray) {
                System.out.println(car.getMakeAndModel() + " is an antique: " + car.isAntique());
            }
        }
    }

    This new main method does several things:

    • It creates two Car objects: a modern car and a classic car.
    • It calls our new accelerate and brake methods on the modern car.
    • It uses the getMakeAndModel and isAntique methods on the classic car.
    • It creates an array of Car objects and uses a for-each loop to iterate over them, demonstrating how we can work with collections of objects.
  6. Save both files, then compile and run the CarDemo program:

    javac ~/project/Car.java ~/project/CarDemo.java
    java -cp ~/project CarDemo

    You should see output similar to this:

    Car Information:
    Make: Toyota
    Model: Corolla
    Year: 2022
    The Toyota Corolla is accelerating.
    The Toyota Corolla is braking.
    Ford Mustang is an antique: true
    Toyota Corolla is an antique: false
    Ford Mustang is an antique: true

Congratulations! You've significantly expanded your Car class and created a more complex program using objects. This demonstrates how object-oriented programming can be used to model real-world concepts in code. Each car object now has its own data (make, model, year) and behavior (accelerate, brake, etc.), just like real cars do.

  1. We added methods to our Car class that represent actions (accelerate() and brake()). These methods don't change the state of the car, but in a more advanced program, they could modify properties like speed or fuel level.
  2. We created a method getMakeAndModel() that combines two pieces of information about the car. This is a common pattern in object-oriented programming – methods that provide convenient access to object data.
  3. The isAntique() method shows how we can use object data (the car's year) along with external information (the current year) to compute new information about the object.
  4. In our CarDemo class, we demonstrated how to create and use multiple objects, how to call various methods on these objects, and how to work with an array of objects.

This example shows the power of object-oriented programming. We've created a Car class that encapsulates both data (make, model, year) and behavior (accelerate, brake, isAntique). Each Car object we create is independent, with its own set of data, but they all share the same set of behaviors defined by the class.

Summary

In this lab, we've taken a significant step forward in our Java programming journey. We've covered some fundamental concepts that are crucial for writing more complex and organized Java programs. Let's recap what we've learned:

  1. Methods:

    • We created and used methods to organize our code and make it more reusable.
    • We saw how methods can take parameters and return values, allowing us to break down complex problems into smaller, manageable pieces.
    • Methods help us avoid repeating code and make our programs easier to understand and maintain.
  2. Classes and Objects:

    • We introduced the concept of classes as blueprints for objects.
    • We created a Car class with attributes (make, model, year) and methods (displayInfo, accelerate, brake, etc.).
    • We learned how to create objects (instances of a class) and call methods on these objects.
  3. Object-Oriented Programming:

    • We saw how object-oriented programming allows us to model real-world concepts in our code.
    • We encapsulated data (attributes) and behavior (methods) within our Car class.
    • We created multiple Car objects, demonstrating how each object has its own set of data but shares the same behaviors defined by the class.
  4. Enhanced Class Functionality:

    • We expanded our Car class with more complex methods, including one that uses Java's built-in date functionality to determine if a car is an antique.
    • We saw how methods can interact with object data and external information to compute new results.
  5. Working with Multiple Objects:

    • We created an array of Car objects, demonstrating how we can work with collections of objects in our programs.

These concepts form the foundation of Java programming and are essential for building larger, more complex applications. As you continue your Java journey, you'll find yourself using these concepts constantly.

Remember, the key to mastering programming is practice. Here are some ideas to extend your learning:

  1. Try adding more attributes to the Car class, like color or mileage.
  2. Create methods that modify these attributes, like paint(String newColor) or drive(int miles).
  3. Create a Garage class that can store multiple Car objects. Add methods to add cars to the garage, remove cars, and display all cars in the garage.
  4. Experiment with creating classes for other types of objects, like Book or Student.

Keep coding, keep experimenting, and most importantly, keep having fun! You're well on your way to becoming a proficient Java programmer.

Other Java Tutorials you may like