• Menu
  • Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

JavaBeat

Java Tutorial Blog

  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)

How To Master Polymorphism In Java – Understanding Polymorphism

November 6, 2018 //  by Krishna Srinivasan//  Leave a Comment

Understanding the concept of polymorphism is key to mastering the Java programming language. However, the concept can be a tricky one. What is the best way to understand the concept of polymorphism and how to apply it to our Java programming?

The Origin of Polymorphism

The Origin of Polymorphism

Perhaps the best way to understand the definition of polymorphism in Java is to examine the simple English definition of the word. Polymorphism is the act of being polymorphous, which is to pass through many or various stages, forms, or the like. So, we know that, in typical English usage, polymorphism is the act of changing—of being able to pass through many different stages or forms, some possibly at the same time. This gives us a clue as to what polymorphism means in Java but doesn’t satisfy our need for a definition completely.

The next step could be to examine the usage of the word in other STEM fields, such as biology. The biological definition is similar to the definition listed above — lists the biological definition of polymorphism as “the existence of an organism in several form or color varieties.” In Crystallography polymorphism is defined as crystallization into two or more chemically identical but crystallographically distinct forms, which seems perhaps a bit closer to the definition that we are looking for regarding Java. Finally, in Genetics, the definition of polymorphism is the presence of two or more distinct phenotypes in a population due to the expression of different alleles of a given gene, as human blood groups O, A, B, and AB. While this seems far removed from the world of polymorphism in Java and computers, again we find the idea of different “varieties” (in this case, blood types) of the same “object” (in this case, blood).

So, at least in biology and the “real” world, we know that polymorphism has to do with multiple forms of the same object. However, the definition of the word and the application of the concepts behind it are a little different (and trickier) in Java. To understand polymorphism in Java, you must first be able to understand that Java is object-oriented programming.

A Quick Summary of Object-Oriented Programming

Object-Oriented Programming

Unlike some other programming languages, Java is an object-oriented language. This trait means that all programming in Java consists of creating objects with attributes and assigning behaviors(known as methods) to those objects. Other types of programming such as BASIC and PASCAL are considered procedure-oriented programming. Procedure-oriented programming concentrates on written instruction sets in order to accomplish tasks. The term “subroutines” is commonly associated with procedure-oriented programming, and while this type of programming still has its adherents, it generally is seen as less modern and subsequently less popular.

Java, like many object-oriented programming languages, also allows inheritance, in which parent objects (also known as the superclass of objects) can pass attributes down to their child objects. The programmer can determine the attributes of an object by using an IS-A test. While this test may sound complicated, it actually is quite simple. For example, if the coder creates an animal object as a parent and a cat object as a child, the programmer can simply test the relationship by seeing if the cat object is an animal object. In this case, it would be, and so the relationship is confirmed.

But how does polymorphism in Java affect these procedures? Well, it’s simple. A Java object is polymorphic if it passes the IS-A test for more than more class. For example, the cat object listed above is polymorphic. The cat object IS-A animal object, and it is also a cat object. The cat object falls under two distinct categories and therefore is an example of polymorphism in Java.

Using Polymorphism in Java

Using Polymorphism in Java

“Wait a second!”, some of the more adroit among our readers may claim. That means that EVERY object in Java displays polymorphism, because all objects exist as their type, and as their class object. That is correct, according to tutorialspoint.com. All objects within Java are polymorphic. So if you create an array as an object in the “Cool Array” class, the IS-A test would confirm that the object IS-A array ( as its type) and would also confirm that the array IS-A member of the “Cool Array” class.

In practice, this functionality of Java objects can be quite useful. In our Cat example, the coder wouldn’t need to recode all of the Animal attributes. Because of inheritance and polymorphism in Java, the Cat object would simply inherit all of the animal attributes with no further work necessary. Again, the cat object IS-A animal object and it IS-A cat object. But suppose the coder wanted to create a “subspecies” of cat within this framework? What would the coder do then?

Once again, the answer is simple. The coder should simply extend the class of cat to, say, “mountain cat” and then list the attributes that the coder wishes the cat to have. For example, if the coder wishes for the “mountain cat” object to have big whiskers, then they can simply assign it to have such. Even better, because of inheritance and polymorphism, the “mountain cat” class extension will have all of the attributes of both the Animal class and the “Cat class”. The mountain cat class extension IS-A animal class and IS-A cat class.

Overriding in Java – A Brief Look

Overriding in Java – A Brief Look

What happens though, if the parent class already has an attribute that the coder wishes to change? For instance, if the class “Cat” already has short whiskers listed as an attribute, how could the “Mountain Cat” class extension has long whiskers instead. The answer is simple. When a parent class’s attribute comes into conflict with a child class’s attribute, the child object’s attribute will override the parent class’s attribute. This procedure is known as overriding, and the Java compiler determines it at runtime.

As some readers may already be aware, Java is a compiled language, which means that a program written in this language must pass through an interpreter which translates Java to a machine code. Other languages, such as Python, interpret as the program is running. Overriding takes place AFTER the program is compiled, so the procedure is known as dynamic(or late binding). Overriding isn’t the only instance of dynamic binding, but it is one of the most common. All instances of dynamic binding take place at runtime—while the program is running. That feature is what defines dynamic (or late) binding.

Just a quick reminder, while technically all of Java’s methods are virtual (meaning they can be changed) until labeled as final, using dynamic(also known as late) binding is probably the best solution for emulating C’s Virtual Method. This functionality could only have been made possible due to the possibilities of polymorphism in Java.

Overloading in Java – A Summary

Overloading in Java

While overriding may be intuitive, the concept of overloading may not come quite so easily to the beginning Java programmer. Overloading can only take place when an object contains multiple methods. The compiler identifies each method within the object by its method signature, which is the method’s name and parameter list. Even if the method name is the same across multiple methods, as long as the parameters are different for each method, this technique will successfully be completed.

Except as noted above, the program using overloading is typed and compiled normally. As the program using this technique is being compiled, the compiler will make a decision regarding which method to use by comparing the values in the reference variables to the parameters listed in the method signature and choosing appropriately. An example of this technique is below, modified from an example provided by sitepoint.com.

class DemoOverload{

public int add(int x, int y){ //method 1

return x+y;

}

public int add(int x, int y, int z){ //method 2

return x+y+z;

}

public int add(int w, int x, int y, int z){ //method 3

return w+x+y+z

}

If the coder were to call the class listed above using the following: System.out.println(demo.add(2,3));, then method 1 would be chosen by the compiler, as the parameters match the reference variables. If, instead we called the class written above using System.out.println(demo.add(1,2,3,4));, then method 3 would be called due to the same reason.

Because this action takes place during compilation, this technique is known as compile time polymorphism or as static binding. Overloading is the most common example of compile time polymorphism and has the following rules. The return types may be different for each method. Also, different exceptions may be thrown for each method, which can be useful. Finally, the differing methods may have varying access modifiers. There are other techniques using compile time polymorphism (or static binding), but overloading is the most common and is useful to know at all skill levels of programming.

Understanding polymorphism in Java is key to success in Java for all levels of programming. Many useful techniques such as overriding and overloading arise from mastering polymorphism in Java – the language is objectively weaker without it. While other languages also offer polymorphism, it could be argued that polymorphism in Java is the most successful implementation. The implementation of polymorphism in Java is both flexible and easy to understand. Learning polymorphism in Java should be considered invaluable in furthering a coder’s Java programming career.

Category: JavaTag: mastering polymorphism java, polymorphism java, polymorphism java summary

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Previous Post: «How To Use The Palindrome Function in Java How To Use The Palindrome Function In Java – Methods And Examples
Next Post: How To Master Multithreading in 2 Different Programming Languages How to Master Multithreading in 2 Different Programming Languages»

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Follow Us

  • Facebook
  • Pinterest

FEATURED TUTORIALS

New Features in Spring Boot 1.4

Difference Between @RequestParam and @PathVariable in Spring MVC

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Introductiion to Jakarta Struts

What’s new in Struts 2.0? – Struts 2.0 Framework

JavaBeat

Copyright © by JavaBeat · All rights reserved
Privacy Policy | Contact