Loading subject…
Polymorphism
Polymorphism means “many forms” - the ability of objects to take on different forms depending on context.
Java: two real methods exist, and the compiler picks one from the argument types.
Python: only one method exists, and a default parameter covers both calls.
Java
Python
Using the Animal, Dog and Cat classes above, one loop produces three different outputs.
class MathOps { int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
int add(int a, int b, int c) { return a + b + c; }}
MathOps m = new MathOps();m.add(2, 3); // calls the int versionm.add(2.5, 3.5); // calls the double versionm.add(1, 2, 3); // calls the three-parameter versionclass MathOps: def add(self, a, b=0, c=0): return a + b + c
m = MathOps()m.add(2, 3) # 5m.add(2, 3, 4) # 9
# Writing a second def add(self, a, b, c) here would simply# replace the first one. Python keeps only the last definition.class Animal { void sound() { System.out.println("Animal makes a sound"); }}
class Dog extends Animal { @Override void sound() { super.sound(); // parent version first System.out.println("Dog barks"); }}
class Cat extends Animal { @Override void sound() { System.out.println("Cat meows"); }}class Animal: def sound(self): print("Animal makes a sound")
class Dog(Animal): def sound(self): super().sound() # parent version first print("Dog barks")
class Cat(Animal): def sound(self): print("Cat meows")Animal[] pets = { new Animal(), new Dog(), new Cat() };
for (Animal pet : pets) { pet.sound(); // declared type Animal, actual object decides}
// Animal makes a sound// Animal makes a sound// Dog barks// Cat meowspets = [Animal(), Dog(), Cat()]
for pet in pets: pet.sound() # the object decides which version runs
# Animal makes a sound# Animal makes a sound# Dog barks# Cat meows