OOP

Class & Object

Class & Object

1. Class

A class is a blueprint/template used to create objects.

It defines the object's data (fields) and behavior (methods).

class Car {
String brand;
int speed;
void drive() {
System.out.println("Car is driving");
}
}
PartExamplePurpose
ClassCarBlueprint
FieldString brandStores data
Fieldint speedStores data
Methoddrive()Defines behavior

2. Object

An object is an instance of a class that contains its own state and can perform behaviors defined by the class.

Objects are created using the new keyword.

Car car1 = new Car();
car1.brand = "BMW";
car1.speed = 120;
car1.drive();
ConceptExample
ClassCar
Objectcar1
Create objectnew Car()
Access fieldcar1.brand
Call methodcar1.drive()

4. Class vs Object

ClassObject
Blueprint/templateInstance of a class
Logical definitionReal entity created from class
Does not represent one specific instanceRepresents a specific instance
Example: CarExample: car1
Created using classCreated using new
Next TopicConstructor, this, static