Polymorphism in object oriented programming.

Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object.

Any java object that can pass more than one IS-A test is considered to be polymorphic. In Java, all java objects are polymorphic since any object will pass the IS-A test for their own type and for the class Object.

It is important to know that the only possible way to access an object is through a reference variable. A reference variable can be of only one type. Once declared the type of a reference variable cannot be changed.

 

 

 

The reference variable can be reassigned to other objects provided that it is not declared final. The type of the reference variable would determine the methods that it can invoke on the object.

A reference variable can refer to any object of its declared type or any subtype of its declared type. A reference variable can be declared as a class or interface type.

In the video tutorial we explain the concept using the code below:

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

}
public class B {
	public void print() {
		System.out.println("B");
	}

}

public class C extends B {
	public void print() {
		System.out.println("C");
	}

}

public class Main {
	public static void main(String[] args) {
		B[] bs = new B[3];
		bs[0] = new B();
		bs[1] = new A();
		bs[2] = new C();
		naivePrinter(bs);

	}

	private static void naivePrinter(B[] bs) {
		for (int i = 0; i < bs.length; i++) {
			bs[i].print();
		}

	}
}

<< Previous Next >>