In Java, a class is a blueprint or a template that defines the characteristics and behaviors of an object. A class is a user-defined data type that encapsulates data and behavior into a single unit. It is used to create objects, which are instances of the class.
An object, on the other hand, is an instance of a class. It represents a specific realization of the class blueprint, with its own set of values for the class’s variables.
Here’s an example Java program that demonstrates the difference between a class and an object:
public class Car {
private String make;
private String model;
private int year;
public Car(String make, String model, int year) {
this.make = make;
this.model = model;
this.year = year;
}
public String getMake() {
return make;
}
public void setMake(String make) {
this.make = make;
}
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;
}
public static void main(String[] args) {
Car myCar = new Car("Toyota", "Camry", 2020);
System.out.println("My car is a " + myCar.getYear() + " "
+ myCar.getMake() + " " + myCar.getModel() + ".");
}
}
This program defines a class called Car that represents a car. The Car class has three instance variables (make, model, and year) that represent the state of a car, and getter and setter methods for each variable that represent behaviors.
The program then creates an object of the Car class called myCar, with a make value of "Toyota", a model value of "Camry", and a year value of 2020. It then uses the getMake, getModel, and getYear methods of the myCar object to print a message to the console.
In summary, a class is a blueprint or a template that defines the characteristics and behaviors of an object, while an object is an instance of a class that represents a specific realization of the class blueprint, with its own set of values for the class’s variables.