Pillar | Meaning | Example |
---|---|---|
Encapsulation | Hiding internal details and exposing only necessary parts | Using private fields + public getters/setters |
Abstraction | Hiding complex logic behind a simple interface | Using abstract classes or interfaces |
Inheritance | Reusing code by creating new classes from existing ones (IS-A relationship) | class Dog extends Animal |
Polymorphism | One name, many forms depending on context | Overriding or overloading methods |
Feature | Overriding | Overloading |
---|---|---|
Definition | Redefining a method in a subclass | Defining multiple methods with same name but different parameters |
Annotation | @Override required for safety and clarity | No annotation required |
Class Relation | Requires inheritance | Can happen in the same class |
Polymorphism Type | Runtime polymorphism | Compile-time polymorphism |
Type | Definition | Example |
---|---|---|
Compile-Time | Method to call is known at compile time (overloading) | add(int a, int b) vs add(double a, double b) |
Run-Time | Method to call is determined at runtime based on the object’s type | Overridden makeSound() in subclasses |
package myapp.animals;
Feature | Abstract Class | Interface |
---|---|---|
Can have fields? | Yes | No (only constants - public static final) |
Can have methods? | Yes – abstract and concrete | Yes – abstract by default (Java 8+: default & static methods allowed) |
Use case | When classes share common behavior | When unrelated classes share a contract |
Inheritance | extends (only one abstract class) | implements (can implement multiple) |