Interface Based Polymorphic Programming in Java

Polymorphism, i.e. runtime type determination, is very important in Java. Polymorphic programming is generic programming. Here we are not calling methods of concrete classes at the time of coding, instead we are writing generic code, that can allow us to assign desired concrete instances at runtime. Let us take an example-

java.util.List interface represents all lists and is extension of java.util.Collection interface. Concrete implementations are java.util.ArrayList, java.util.LinkedList, java.util.Vector. While writing code you take a freedom of using the generic type i.e. List. But at runtime, based on some parameter you determine the concrete class to be used. This may be a simple list leading to ArrayList, list requiring information of objects around a position leading to LinkedList, or synchronized list suggesting Vector. Thus the program is not strongly typed when Interfaces are used to declare variables wherever possible instead of concrete classes.

To conclude we can say – If we use concrete classes to declare variables, we are indirectly strongly typing our programs, instead use interfaces wherever possible and make the polymorphism principle to work in your program.

Here is a sample code.

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class PolymorphicExample1 {

	public static void main(String[] args) {
		PolymorphicExample1 pex1 = new PolymorphicExample1();
		List returnList = pex1.getList("ArrayList");
	}

	private List getList(String whichList){
		List myList = null;
		if(whichList.equals("ArrayList")){
			myList = new ArrayList();
		}else if(whichList.equals("LinkedList")){
			myList = new LinkedList();
		}
		return myList;
	}
}
  • Share/Bookmark
Java

If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.

Leave Comment

(required)

(required)