Code Example 1: dynamic polymorphism

This Java program demonstrates dynamic polymorphism through method overriding. The A class has a print method that is overridden in the B and C classes. When the main method is called, three objects are created, one each of the A, B, and C classes.

The print method of each object is then called. Since B and C classes override the print method of the A class, the behavior of the print method depends on the type of the object.

When the print method is called on the a object, it will call the print method of the A class and print “overridden method” to the console. When the print method is called on the b object, it will call the print method of the B class and print “overriding method1” to the console. Similarly, when the print method is called on the c object, it will call the print method of the C class and print “overriding method2” to the console.

class A {
	void print() {
		System.out.println("overridden method");
	}
}

class B extends A {
	void print() {
		System.out.println("overriding method1");
	}
}

class C extends A {
	void print() {
		System.out.println("overriding method2");
	}
}

public class DynamicPolymorphism {
	public static void main(String[] args) {
		A a = new A();
		A b = new B();
		A c = new C();

		a.print();
		b.print();
		c.print();
	}
}
Output
overridden method
overriding method1
overriding method2