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:
- Create a class called
Car
with the attributes Make
, Model
, and Year
.
- Add a constructor that initializes these attributes.
- Add a
ShowDetails()
method that prints the attribute values.
- In the main method, create an object of the
Car
class and initialize its attributes using the constructor.
- 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.
View Example Code
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.