๐ Introduction
Java is a purely object-oriented language (except for primitive types). OOP (Object-Oriented Programming) is all about organizing code around objects โ real-world entities that have state (fields) and behavior (methods).
In this lesson, you’ll learn the 4 pillars of OOP in Java and how to build your own classes and objects.
๐น What is an Object?
An object is an instance of a class. Think of a class as a blueprint, and objects as the actual products created from that blueprint.
๐น Defining a Class
public class Car {
// properties (fields)
String color;
int speed;
// method
void drive() {
System.out.println("Driving at " + speed + " km/h");
}
}
๐น Creating an Object
public class Main {
public static void main(String[] args) {
Car myCar = new Car(); // creating object
myCar.color = "Red";
myCar.speed = 80;
myCar.drive(); // call method
}
}
๐๏ธ 4 Pillars of OOP in Java
1. โ Encapsulation โ Data Hiding
Wrap data (fields) and methods inside a class. Use private
for fields and public
for methods to protect data.
public class Person {
private String name; // private = encapsulated
public void setName(String newName) {
name = newName;
}
public String getName() {
return name;
}
}
2. โ Inheritance โ Reuse Code
One class (child) inherits from another (parent). This allows code reuse and method overriding.
class Animal {
void sound() {
System.out.println("Animal sound");
}
}
class Dog extends Animal {
void sound() {
System.out.println("Bark");
}
}
3. โ Polymorphism โ One Interface, Many Forms
Allows you to use the same method name but different implementations.
Animal a = new Dog(); // Polymorphism
a.sound(); // Output: Bark
4. โ Abstraction โ Hide Complex Details
Use abstract
classes or interfaces to hide implementation and only show essential features.
abstract class Shape {
abstract void draw();
}
class Circle extends Shape {
void draw() {
System.out.println("Drawing Circle");
}
}
๐ง Constructor โ A Special Method
A constructor is called when an object is created. It initializes the object.
class Student {
String name;
Student(String n) {
name = n;
}
}
๐งช Practice Example
class BankAccount {
private double balance;
public void deposit(double amount) {
balance += amount;
}
public double getBalance() {
return balance;
}
}
public class Main {
public static void main(String[] args) {
BankAccount acc = new BankAccount();
acc.deposit(1000);
System.out.println("Balance: " + acc.getBalance());
}
}
โ What You Learned
- OOP revolves around classes and objects
- The 4 Pillars: Encapsulation, Inheritance, Polymorphism, Abstraction
- How to define and use classes, constructors, and access modifiers