Java OOP Concepts with Polymorphism
1. Difference Between Runtime and Compile-Time Polymorphism
| Feature | Compile-Time Polymorphism | Runtime Polymorphism |
|---------------------|----------------------------------|-------------------------------|
| Also Known As | Method Overloading | Method Overriding |
| Decision Made At | Compile time | Runtime |
| Achieved Through | Overloading | Inheritance + Overriding |
| Speed | Faster | Slightly slower |
| Example | add(int, int) vs add(double, double) | Overriding toString() method |
2. Runtime Polymorphism
- Definition: Method resolved at runtime
- Uses inheritance + overriding
- Advantage: Dynamic behavior
- Disadvantage: Slightly slower
Example:
class Animal { void sound() {} }
class Dog extends Animal { void sound() { System.out.println("Dog barks"); } }
Animal a = new Dog();
a.sound(); // Output: Dog barks
3. Compile-Time Polymorphism
- Definition: Method resolved at compile time
- Achieved by method overloading
- Faster but less flexible
Example:
class Calculator {
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
4. Class and Object (OOP Basics)
Java OOP Concepts with Polymorphism
Class: Blueprint for object
Object: Instance of a class
Example:
class Car {
String color;
void drive() { System.out.println("Driving"); }
Car c = new Car();
5. Java Introduction
- Object-oriented
- Platform-independent (WORA)
- Secure, robust, and multi-threaded
6. Variables, Operators, ArrayList
Variables store data
Operators: +, -, *, ==, etc.
ArrayList Example:
ArrayList<String> list = new ArrayList<>();
list.add("Apple");
list.remove("Apple");
7. Constructor Details
- Used for initializing objects
- Types: Default, Parameterized
Example:
class Student {
Student(String n) { name = n; }
8. Encapsulation
Java OOP Concepts with Polymorphism
- Wrapping variables and methods in a class
- Use private vars with public getters/setters
Example:
private int balance;
public int getBalance() { return balance; }
9. Polymorphism Details
- Object takes many forms
- Types: Overloading (Compile-Time), Overriding (Runtime)
Example:
void print(String s)
void print(int i)