Class and Object
In object-oriented design, a class is a blueprint or template for creating objects. It defines the structure and behavior that the objects of that class will have.
Let's take an example of a Car
class:
1public class Car {
2 private String make;
3 private String model;
4 private int year;
5
6 public Car(String make, String model, int year) {
7 this.make = make;
8 this.model = model;
9 this.year = year;
10 }
11
12 public void drive() {
13 System.out.println("Driving the " + make + " " + model + "...");
14 }
15}
In this example, the Car
class has three attributes: make
, model
, and year
. These attributes represent the characteristics of a car. Additionally, the class has a method drive()
, which defines the behavior of a car.
An object is an instance of a class. It represents a specific real-world entity or a concept. For example, we can create an object myCar
from the Car
class:
1Car myCar = new Car("Toyota", "Camry", 2021);
In this case, myCar
is an object of the Car
class, which has its own set of attribute values. We can call the drive()
method on myCar
to perform the specific behavior defined in the class.
1myCar.drive();
The output of the above code will be:
1Driving the Toyota Camry...
In summary, a class serves as a blueprint for creating objects, while objects are instances of a class that have their own attribute values and can perform specific behaviors defined in the class.
xxxxxxxxxx
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 void drive() {
System.out.println("Driving the " + make + " " + model + "...");
}
}