Ability of an organism to take different shapes is polymorphism in bio world. A simplest definition in computer terms would be, handling different data types using the same interface. In this tutorial, we will learn about what is polymorphism in computer science and how polymorphism can be used in Java.

I wish this tutorial will help address the following,

  • is overloading polymorphism?
  • is overriding polymorphism?
  • Ad hoc Polymorphism
  • Parametric Polymorphism
  • Coercion Polymorphism
  • Inclusion or subtype Polymorphism
  • what is static-binding?
  • what is dynamic binding?

Types of Polymorphism

Polymorphism in computer science was introduced in 1967 by Christopher Strachey. Please let me know with reference if it is not a fact and the tutorial can be updated. Following are the two major types of polymorphism as defined by Strachey.

  1. Ad hoc Polymorphism
  2. Parametric Polymorphism

Later these were further categorized as below:

Ad hoc Polymorphism

"Ad-hoc polymorphism is obtained when a function works, or appears to work, on several different types (which may not exhibit a common structure) and may behave in unrelated ways for each type.  Parametric polymorphism is obtained when a function works uniformly on a range of types; these types normally exhibit some common structure." – Strachey 1967

If we want to say the above paragraph in two words, they are operator overloading and function overloading. Determining the operation of a function based on the arguments passed.

Ad hoc Polymorphism in Java

In Java we have function overloading and we do not have operator overloading. Yes we have “+” operator implemented in a polymorphic way.

String fruits = "Apple" + "Orange";
int a = b + c;

The definition is when the type is different, the internal function adjusts itself accordingly. int and float are different types and so even the following can be included in polymorphism operator overloading.

int i = 10 - 3;
float f = 10.5 - 3.5;

Similarly even * and / can be considered as overloaded for int and float types.

Having said all the above, these are all language implemented features. Developers cannot custom overload an operator. So answer for the question, “does Java supports operator overloading?” is “yes and no”.

Java wholeheartedly supports function overloading. We can have same function name with different argument type list. For function overloading in Java I have already written a super-hit tutorial and I am sure you will enjoy reading it.

In inheritance, the ability to replace an inherited method in the subclass by providing a different implementation is overriding. Function overriding in is discussed in the same tutorial as overloading.

Polymorphism is a larger concept which consists of all these different types. So it is not right to say that overloading or overriding alone is polymorphism. It is more than that.

Coercion Polymorphism

Implicit type conversion is called coercion polymorphism. Assume that we have a function with argument int. If we call that function by passing a float value and if the the run-time is able to convert the type and use it accordingly then it is coercion polymorphism.

Now with this definition, let us see if Java has coercion polymorphism. The answer is half yes. Java supports widening type conversion and not narrowing conversions.

Narrowing Conversion

class FToC {
public static float fToC (int fahrenheit) {
return (fahrenheit - 32)*5/9;
} public static void main(String args[]) {
System.out.println(fToC(98.4));
}
}

Java does not support narrowing conversion and we will get error as "FToC.java:7: fToC(int) in FToC cannot be applied to (double)"

Widening Conversion

class FToC {
public static float fToC (float fahrenheit) {
return (fahrenheit - 32)*5/9;
} public static void main(String args[]) {
System.out.println(fToC(98));
}
}

The above code will work without an error in Java. We are passing an int value ’98’ wherein the expected value type is a float. Java implicitly converts int value to float and it supports widening conversion.

Universal Polymorphism

Universal polymorphism is the ability to handle types universally. There will be a common template structure available for operations definition irrespective of the types. Universal polymorphism is categorized into inclusion polymorphism and parametric polymorphism.

Inclusion polymorphism (subtype polymorphism)

Substitutability was introduced by eminent Barbara Liskov and Jeannette Wing. It is also called as Liskov substitution principle.

“Let T be a super type and S be its subtype (parent and child class). Then, instances (objects) of T can be substituted with instances of S.”

Replacing the supertype’s instance with a subtype’s instance. This is called inclusion polymorphism or subtype polymorphism. This is covariant type and the reverse of it is contravariant. We have discussed the substitution principle and covariant types, contravariant and invariant earlier in the linked tutorial. This is demonstrated with a code example. Java supports subtype polymorphism from Java / JDK version 1.5.

Parametric Polymorphism

Here we go, we have come to ‘Generics’. This is a nice topic and requires a full detailed tutorial with respect to Java. For now, parametric polymorphism is the ability to define functions and types in a generic way so that it works based on the parameter passed at runtime. All this is done without compromising type-safety.

The following source code demonstrates a generics feature of Java. It gives the ability to define a class and parameterize the type involved. The behavior of  the class is based on the parameter type passed when it is instantiated.

package com.javapapers.java;

import java.util.ArrayList;
import java.util.List; public class PapersJar {
private List itemList = new ArrayList(); public void add(T item) {
itemList.add(item);
} public T get(int index) {
return itemList.get(index);
} public static void main(String args[]) {
PapersJar papersStr = new PapersJar();
papersStr.add("Lion");
String str = papersStr.get(0);
System.out.println(str); PapersJar papersInt = new PapersJar();
papersInt.add(new Integer(100));
Integer integerObj = papersInt.get(0);
System.out.println(integerObj);
}
}

Static Binding vs Dynamic Binding

Give all the above polymorphism types, we can classify these under different two broad groups static binding and dynamic binding. It is based on when the binding is done with the corresponding values. If the references are resolved at compile time, then it is static binding and if the references are resolved at runtime then it is dynamic binding. Static binding and dynamic binding also called as early binding and late binding. Sometimes they are also referred as static polymorphism and dynamic polymorphism.

Let us take overloading and overriding for example to understand static and dynamic binding. In the below code, first call is dynamic binding. Whether to call the obey method of DomesticAnimal or Animal is resolve at runtime and so it is dynamic binding. In the second call, whether the method obey() or obey(String i) should be called is decided at compile time and so this is static binding.

package com.javapapers.java;

public class Binding {

	public static void main(String args[]) {
Animal animal = new DomesticAnimal();
System.out.println(animal.obey()); DomesticAnimal domesticAnimal = new DomesticAnimal();
System.out.println(domesticAnimal.obey("Ok!"));
}
} class Animal {
public String obey() {
return "No!";
} } class DomesticAnimal extends Animal {
public String obey() {
return "Yes!";
} public String obey(String i) {
return i;
}
}

Output:

Yes!

Ok!

Advantages of Polymorphism

  • Generics: Enables generic programming.
  • Extensibility: Extending an already existing system is made simple.
  • De-clutters the object interface and simplifies the class blueprint.

Java Polymorphism的更多相关文章

  1. java url demo

    // File Name : URLDemo.java import java.net.*; import java.io.*; public class URLDemo { public stati ...

  2. Android学习笔记之DocumentBuilder的使用....

    PS:当你的才华还撑不起你的野心时,那你需要静下心来学习..... 学习内容: 1.从服务器上获取XML文档... 2.解析XML文档中的内容...   XML文件想必大家都非常的熟悉,可扩展的标记语 ...

  3. go 学习笔记之无心插柳柳成荫的接口和无为而治的空接口

    如果你还了解编程概念中的接口概念,那么我建议你最好还是先阅读上一篇文章.详情请点击 go 学习笔记之万万没想到宠物店竟然催生出面向接口编程? ,否则的话,请自动忽略上文,继续探索 Go 语言的接口有什 ...

  4. Spark案例分析

    一.需求:计算网页访问量前三名 import org.apache.spark.rdd.RDD import org.apache.spark.{SparkConf, SparkContext} /* ...

  5. java面向对象之 多态 Polymorphism

    多态(Polymorphism):用我们通俗易懂的话来说就是子类就是父类(猫是动物,学生也是人),因此多态的意思就是:父类型的引用可以指向子类的对象. 1.多态的含义:一种类型,呈现出多种状态 主要讨 ...

  6. Java Jackson - Json Polymorphism

    from://http://www.studytrails.com/java/json/java-jackson-Serialization-polymorphism.jsp Jackson prov ...

  7. Java基础-面向对象第三大特性之多态(polymorphism )

    Java基础-面向对象第三大特性之多态(polymorphism) 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.多态概述 多态是继封装,继承之后,面向对象的第三大特性,多态的 ...

  8. Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(八)之Polymorphism

    Polymorphism is the third essential feature of an object-oriented programming language,after data ab ...

  9. Java学习笔记——多态性Polymorphism

    Java中实现多态的机制 Java中实现多态的机制靠的是父类或者接口定义的引用变量可以指向子类或者具体的实现类的实例对象,而程序调的方法在运行期才动态绑定,就是引用变量所指向的具体实例对象的方法,也就 ...

随机推荐

  1. 复习:C语言基础知识1

    占位符: %d, %i,代表整数,%f-浮点,%s,字符串,%c,char. %p 指针,%fL 长long,%e科学计数,%g 小数或科学计数. C语言中的格式占位符: %a,%A 读入一个浮点值( ...

  2. SpringBootSecurity学习(25)前后端分离版之OAuth2.0 令牌中继

    增加Eureka 前面介绍的项目都是授权服务和资源服务单独两个,这样在资源服务中的 check_token 地址都是写死的地址 : 下面我们把eureka加上,这样就可以直接用服务名了.eureka服 ...

  3. Oracle For Linux 恢复日记 霆智X8III

    公司最近的客户需要在LINUX系统中做数据迁移,备份出来的内容数据库物理文件,回档日志和SpfileXXXX 客户用的是北京霆智的X8备份阵列,X8与数据库服务器都放在IDC机所,IDC机房与客户之间 ...

  4. C# 网络连接中异常断线的处理:ReceiveTimeout, SendTimeout 及 KeepAliveValues(设置心跳)

    C# 网络连接中异常断线的处理:ReceiveTimeout, SendTimeout 及 KeepAliveValues(设置心跳) 在使用 TcpClient 网络连接中常常会发生客户端连接异常断 ...

  5. sql server 根据字段去重

    使用 row_number() over (partition by 要去重的字段 order by 排序字段) 数据库表结构 学生成绩表 UserGrade Id        int       ...

  6. 使用Supervisord软件管理go服务进程

    一.介绍Supervisord软件1.什么是Supervisord?Supervisord是一个非常优秀的进程管理工具,使用Python开发.它可以在类UNIX系统的方式让用户来准确地监视和控制后台一 ...

  7. Java自学-接口与继承 抽象类

    Java 抽象类 在类中声明一个方法,这个方法没有实现体,是一个"空"方法 这样的方法就叫抽象方法,使用修饰符"abstract" 当一个类有抽象方法的时候,该 ...

  8. Matlab享元模式

    享元模式(Flyweight)通过共享技术实现相同或相似对象的重用,可以减少创建对象的数量,以减少内存占用和提高性能.Java String的常量池,python logging,线程池,数据库连接池 ...

  9. 【转载】C#通过InsertAt方法在DataTable特定位置插入一条数据

    在C#中的Datatable数据变量的操作过程中,可以通过DataTable变量的Rows属性的InsertAt方法往DataTable的指定位置行数位置插入一个新行数据,即往DataTable表格指 ...

  10. Java深入学习(5):锁

    可重入锁: 简单来说,支持重复加锁,有可重用性 特征:锁可以传递,方法递归传递 目的:避免了死锁现象 代码: public class Test implements Runnable { @Over ...