its a paradigm based on concept of objects which combines data (attributes) and behavior (methods).
class
it is a blueprint or template for creation of an object. it defines - attributes - data stored in objects (variables). - methods - behaviors or functions that object can perform
- a class encapsulates data and behavior, supporting oop principles like encapsulation, inheritance and polymorphism.
- contains fields, methods, constructors and optionally other classes and interfaces.
class Car {
// Fields
String model;
int year;
// Constructor
Car(String model, int year) {
this.model = model;
this.year = year;
}
// Method
void displayInfo() {
System.out.println("Model: " + model + ", Year: " + year);
}
}
creating objects
- an object is an instance of a class, created from class blueprint.
- objects are created using
newkeyword which allocated memory to the heap. - a constructor is called during object creation to initlialize fields.
- each object has its own copy of instance variables but shares the class’s methods.
public class Main {
public static void main(String[] args) {
// Creating objects
Car car1 = new Car("Toyota", 2020);
Car car2 = new Car("Honda", 2022);
// Accessing object methods
car1.displayInfo(); // Outputs: Model: Toyota, Year: 2020
car2.displayInfo(); // Outputs: Model: Honda, Year: 2022
}
}
assigning object reference variables
- variables of a class type are references to object.
- a reference variable holds the memory address of an object on the heap.
- assigning one variable to another variables make both point to the same object
- objects are not duplicated during assignment. only references are copied
- setting a references to null removes its association with any object, making the object eligible for garbage collection.
public class Main {
public static void main(String[] args) {
// Create objects
Car car1 = new Car("Toyota", 2020);
Car car2 = new Car("Honda", 2022);
// Assigning object reference
Car ref = car1; // ref now points to the same object as car1
ref.displayInfo(); // Outputs: Model: Toyota, Year: 2020
// Modify object via ref
ref.model = "Nissan";
car1.displayInfo(); // Outputs: Model: Nissan, Year: 2020 (car1 reflects change)
// Set car1 to null
car1 = null;
ref.displayInfo(); // Still works: Model: Nissan, Year: 2020 (ref still points to object)
// car1.displayInfo(); // Would throw NullPointerException
}
}