Sobes.tech
Junior — Middle

Can you explain the differences between real and fake polymorphism in programming?

sobes.tech AI

Answer from AI

In programming, polymorphism refers to the ability of objects of different classes to respond to the same messages (methods) in different ways.

  • True (dynamic) polymorphism is implemented through inheritance and method overriding. In Java, this is achieved using virtual methods and mechanisms such as interfaces and abstract classes. The method call is determined at runtime, allowing objects to behave differently depending on their actual type.

  • Fictitious (static) polymorphism is method overloading, where multiple methods have the same name but different parameters. The specific method is chosen at compile-time, not at runtime.

Example:

class Animal {
    void sound() { System.out.println("Some sound"); }
}

class Dog extends Animal {
    @Override
    void sound() { System.out.println("Bark"); }
}

// True polymorphism
Animal a = new Dog();
a.sound(); // Outputs "Bark"

// Fictitious polymorphism (overloading)
class Printer {
    void print(int i) { System.out.println(i); }
    void print(String s) { System.out.println(s); }
}