Tag Archives: Polymorphism

Object Oriented Concepts and Much More

These articles explain the object oriented concepts in detail. UML representation of most of the concept is provided in these articles. Also Java code examples are available to explain the concepts better.  Here is the list of articles.

Polymorphism in Object Oriented Programming

Polymorphism means poly multiple forms. Many shapes. In object oriented programming, polymorphism means the type of object is determined as late as at runtime. What does it mean, and what do we achieve by this? Let us take an example. We have following classes.

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;
	}
}
Powered by WordPress | Designed by: seo service | Thanks to seo company, web designers and internet marketing company