The core pillars of Object-Oriented Programming explained with runnable code.
Blueprint vs Instance. The core building blocks.
class Car { String brand; // Attribute void honk() { // Method System.out.println("Beep!"); }}// Object InstantiationCar myCar = new Car();myCar.brand = "Tesla";
Hiding internal state and requiring access via methods.
class Account { private double balance; // Hidden public double getBalance() { return balance; // Accessor } public void deposit(double amount) { if (amount > 0) balance += amount; }}
Deriving new classes from existing ones (IS-A relationship).
class Animal { void eat() { System.out.println("Eating..."); }}// Dog IS-A Animalclass Dog extends Animal { void bark() { System.out.println("Woof!"); }}Dog d = new Dog();d.eat(); // Inherited method
One interface, many forms. Methods behave differently based on the object.
class Shape { void draw() {} }class Circle extends Shape { void draw() { System.out.println("◯"); } }class Square extends Shape { void draw() { System.out.println("◻"); } }Shape s = new Circle();s.draw(); // Output: ◯ (Runtime decision)
Hiding complexity. Showing only what is necessary.
abstract class Remote { abstract void powerOn(); // No body}class TVRemote extends Remote { void powerOn() { // Complex IR signal logic hidden here System.out.println("TV is On"); }}
Building complex objects from simpler ones (HAS-A relationship).
class Engine { void start() { ... }}class Car { private Engine engine; // HAS-A Engine Car() { this.engine = new Engine(); }}
Defining a contract of behavior that classes must implement.
interface Playable { void play();}class Guitar implements Playable { public void play() { System.out.println("Strumming..."); }}
Belongs to the class, not the instance. Shared memory.
class Counter { static int count = 0; // Shared Counter() { count++; }}new Counter();new Counter();System.out.println(Counter.count); // 2
Accessing the parent class members or constructor.
class Parent { Parent() { System.out.println("Parent init"); }}class Child extends Parent { Child() { super(); // Call parent constructor System.out.println("Child init"); }}