Reading:  

Quick introduction to Object oriented concepts in Java - Part 2 of series


Concept of Polymorphism

Polymorphism is major building blocks of OOP’s along with abstraction, encapsulation and inheritance. 

There are two type of polymorphism: 

  • Compile time polymorphism (method overloading or static binding)
  • Runtime polymorphism (method overriding or dynamic binding)

Compile time polymorphism

In the type control flow is decided during compile time. Method overloading is best example, in which object will have two or more method with same name but the different method parameters. This parameter is different based on:

  • Type of Parameters: The Java.util.Math.max() has different type of parameter.

    public static double Math.max(double x, double y) {..
    }
    public static float Math.max(float x, float y) {..
    }
    public static intMath.max(intx, inty) {..
    }

  • Count of Parameters: Different number of parameter in the function
    CreateUser(string FirstName, string LastName) {..
    }
    CreateUser(string FirstName, string LastName, string SSN) {..
    }

System.out.println() is overloaded method which accept all different kind of data types in Java.

Run time polymorphism

Runtime polymorphism is also known as method overriding. Method overriding feature helps in implementing inheritance in program.

A real world e.g. Vehicle, an application can have Vehical class, and having specialized sub classes like Car and Bus. The subclasses will override default behavior provided by Vehical class + specific behavior of own.

public class Vehical {
	public void CheckSpeed() {
		System.out.println("Speed is 40");
	}
}

class Car extends Vehical {
	public void CheckSpeed() {
		System.out.println("Speed is 80");
	}
}

class Bus extends Vehical {
	public void CheckSpeed() {
		System.out.println("Speed is 60");
	}
}

CheckSpeed() method will be called, depends on type of actual instance created at runtime e.g.

public class VehicalDemo {
	public static void main(String[] args) {
		Vehical a1 = new Car();
		a1.CheckSpeed(); //Prints Speed is 80

		Vehical a2 = new Bus();
		a2.CheckSpeed(); //Prints Speed is 60
	}
}
 

 

Description

This tutorial will introduce you to Object oriented concepts in Java. Basic definitions and learning with code examples.

This tutorial has subdivided into 7 parts as listed below

  1. Understanding Inheritance    
  2. Understanding Overrides
  3. Understanding Polymorphism
  4. Understanding Abstraction
  5. Understanding Encapsulation
  6. Understanding Interfaces
  7. Understanding Packages

Let us know if you found any error in this tutorial. Your feedback is welcome as always.



Audience

Students seeking a quick overview on Java Programming language and its Object oriented features.

Learning Objectives

Learn Object Oriented concepts in Java language.

Author: Subject Coach
Added on: 10th Mar 2015

You must be logged in as Student to ask a Question.

None just yet!