A class in Java is a blueprint for creating objects. It defines a type by bundling data (fields) and methods that work on the data into a single unit.
public class Car {
// Fields
private String color;
private String model;
private int year;
// Constructor
public Car(String color, String model, int year) {
this.color = color;
this.model = model;
this.year = year;
}
// Methods
public void displayDetails() {
System.out.println("Color: " + color);
System.out.println("Model: " + model);
System.out.println("Year: " + year);
}
// Getter and Setter methods
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
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;
}
}
An object is an instance of a class. When a class is defined, no memory is allocated until an object of that class is created.
To create an object, use the new
keyword followed by the class constructor.
public class Main {
public static void main(String[] args) {
// Creating an object of the Car class
Car myCar = new Car("Red", "Toyota", 2020);
// Accessing methods of the object
myCar.displayDetails();
// Modifying fields using setter methods
myCar.setColor("Blue");
System.out.println("Updated Color: " + myCar.getColor());
}
}