Encapsulation hides the internal state of an object and only exposes controlled ways to access or modify it. This protects data and helps maintain integrity.
class Animal { void sound() { System.out.println("Some sound"); } } class Dog extends Animal { void sound() { System.out.println("Bark"); } } public class Main { public static void main(String[] args) { Animal a = new Dog(); a.sound(); } }
Even though the reference type is Animal, the actual object is Dog. Java calls the overridden method in Dog, so it prints "Bark".
class Calculator { int add(int a, int b) { return a + b; } int add(int a, int b, int c) { return a + b + c; } } public class Main { public static void main(String[] args) { Calculator calc = new Calculator(); System.out.println(calc.add(2, 3)); System.out.println(calc.add(1, 2, 3)); } }
Method overloading allows multiple methods with the same name but different parameters. The calls match the correct method signatures, so outputs are 5 and 6.
Abstraction hides complex implementation details and shows only what is necessary, making it easier to use and understand objects.
OOP organizes code into objects that bundle data and behavior, making large projects easier to maintain, reuse, and understand.
