A class in Java is a blueprint or template for creating objects. It defines the properties (attributes) and behaviors (methods) that all objects of the class will have.
// Class declaration
public class Car {
// Instance variables (attributes)
private String brand;
private String model;
private int year;
// Constructor (used to initialize objects)
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);
}
// Getter and setter methods for encapsulation
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
}
In this example:
Car
brand
, model
, and year
are instance variables (also called fields).Car(String brand, String model, int year)
initializes the object with the provided values for brand
, model
, and year
.displayDetails()
: Prints the details of the car (brand, model, year).getBrand()
, setBrand()
, etc.).An object is an instance of a class. It represents a specific entity with its own state (attributes) and behavior (methods), based on the blueprint defined by its class.
// Using the Car class
public class Main {
public static void main(String[] args) {
// Creating instances (objects) of the Car class
Car car1 = new Car("Toyota", "Camry", 2023);
Car car2 = new Car("Honda", "Accord", 2022);
// Accessing methods and properties of objects
car1.displayDetails(); // Output: Brand: Toyota, Model: Camry, Year: 2023
car2.displayDetails(); // Output: Brand: Honda, Model: Accord, Year: 2022
// Using getter and setter methods
car1.setYear(2024); // Update the year of car1
System.out.println("Updated Year of Car 1: " + car1.getYear()); // Output: Updated Year of Car 1: 2024
}
}
In this Main
class:
Car car1 = new Car("Toyota", "Camry", 2023);
and Car car2 = new Car("Honda", "Accord", 2022);
create two instances (objects) of the Car
class.car1.displayDetails()
and car2.displayDetails()
call the displayDetails()
method on each object to print their respective details.car1.setYear(2024)
updates the year
attribute of car1
, and car1.getYear()
retrieves the updated value.