Methods and Constructors

In this exercise, you will learn how to create and use methods and constructors in Java. You will discover how to organize your code into reusable methods to perform specific tasks, and how to use constructors to initialize objects with default or user-supplied values. Through practical examples, you will improve your understanding of method handling and object creation in Java, two fundamental concepts in object-oriented programming.

Topic

Object-Oriented Programming (OOP)

Java Exercise

In this exercise, you will create a Java program that defines a class named Car. This class will have attributes such as make, model, and year, and a constructor that initializes these attributes. You will also add a method named showDetails() that prints the values ​​of these attributes to the console. Next, you'll instantiate an object of the Car class and use the constructor to assign values ​​to attributes and the method to display the car's details.

Instructions:

  1. Create a class called Car with the attributes Make, Model, and Year.
  2. Add a constructor that initializes these attributes.
  3. Add a ShowDetails() method that prints the attribute values.
  4. In the main method, create an object of the Car class and initialize its attributes using the constructor.
  5. Call the ShowDetails() method to display the car's information.

This exercise will help you understand How to work with methods and constructors in Java, key elements in object-oriented programming.


public class Car {
    // Car class attributes
    String brand;
    String model;
    int year;

    // Constructor to initialize the attributes
    public Car(String brand, String model, int year) {
        this.brand = brand;
        this.model = model;
        this.year = year;
    }

    // Method to display car details
    public void displayDetails() {
        System.out.println("Brand: " + brand);
        System.out.println("Model: " + model);
        System.out.println("Year: " + year);
    }

    public static void main(String[] args) {
        // Create a Car object and initialize its attributes
        Car car1 = new Car("Toyota", "Corolla", 2020);

        // Display car details
        car1.displayDetails();
    }
}

 Output:

Make: Toyota
Model: Corolla
Year: 2020

This program creates an object of the Car class, initializes its attributes using the constructor, and then displays the car's information using the showDetails() method.


 Share this JAVA exercise