Tuesday, July 12, 2016

Static and Dynamic Binding in Java with Example

 

What is Binding in Java?


The connecting (linking) between a method call and method body/definition is called binding in java.

Look at the below figure in which we have defined a class X. It has two methods m1() and m2().

The x.m1(); (method call) is linked with m1() method whereas, x.m2(); is linked with m2() method. This linking is called binding.

Binding in Java

Types of Binding in Java


There are two types of binding in java. They are as follows:

1. Static Binding (also known as Early Binding).
2. Dynamic Binding (also known as Late Binding).

Let’s understand static binding and dynamic binding one by one with example programs.

Static Binding in Java


The binding that happens during compilation is called static binding in java. This binding is resolved at the compiled time by the compiler.

In static binding, the java compiler does not check the type of object to which a particular reference variable is pointing to it.

Java compiler just checks which method is going to be called through reference variable and method definition exists or not.

This binding is also known as early binding because it takes place before the program actually runs. An example of static binding is method overloading.

Let’s take an example program where we will calculate the addition of two and three numbers using the method overloading technique.

Program source code 1:

package methodOverloading; 
public class Addition 
{ 
void add(int x, int y) 
{ 
 int sum = x + y; 
System.out.println("Sum of two numbers: " +sum); 
 } 
void add(int x, int y, int z) 
{ 
 int sum = x + y + z; 
 System.out.println("Sum of three numbers: " +sum); 
 } 
public static void main(String[] args) 
{ 
  Addition a = new Addition(); 
  a.add(10, 20); // Calling add() method with passing two argument values. 
  a.add(20, 30, 40); // Calling add() method with passing three argument values. 
 } 
}
Output: 
       Sum of two numbers: 30 
       Sum of three numbers: 90

In the above preceding code, Java compiler did not check the type of object. It just checked only method call through reference variable and method definition.

If there is any private, final, or static method in a class, all these method binding are called static binding.

Program source code 2:

public class Lion 
{ 
private void eat() 
{ 
 System.out.println("Lion eats flesh"); 
 } 
static void live() 
{ 
 System.out.println("Lion lives in Jungle"); 
} 
public static void main(String[] args) 
{ 
 Lion l = new Lion(); 
 l.eat(); 
 Lion.live(); 
 } 
}
Output: 
       Lion eats flesh 
       Lion lives in Jungle

Why binding of private, static, and final methods are always static binding?


Static binding is better performance-wise because java compiler knows that all such methods cannot be overridden and will always be accessed by object reference variable.

Hence, the compiler doesn’t have any difficulty in binding between a method call and method definition. That’s why binding for such methods is always static.

Dynamic Binding in Java


The binding which occurs during runtime is called dynamic binding in java. This binding is resolved based on the type of object at runtime. In dynamic binding, the actual object is used for binding at runtime.

Dynamic binding is also called late binding or runtime binding because binding occurs during runtime. An example of dynamic binding is method overriding.

Let’s take an example program based on dynamic binding in Java.

Program source code 3:

package dynamicBinding; 
public class Animal 
{ 
void eat() 
{ 
 System.out.println("Animals eat both plants and flesh"); 
 } 
} 
public class Lion extends Animal 
{ 
void eat() 
{ 
 System.out.println("Lions eat flesh because they are carnivore"); 
 } 
} 
public class DynamicBindingTest 
{ 
 public static void main(String[] args) 
 { 
  Animal a = new Animal(); 
   a.eat(); // It will call eat() method of Animal class because the reference variable is pointing to object of animal class. 
  Animal a1 = new Lion(); 
   a1.eat(); // It will call eat() method of Lion class because the reference variable is pointing towards the object of Loin class. 
 } 
}
Output: 
       Animals eat both plants and flesh 
       Lions eat flesh because they are carnivore

In the preceding example, object type cannot be determined by the compiler. Therefore, JVM resolved the method calls based on the type of object at runtime.

Difference between Static and Dynamic Binding in Java


There are the following differences between static and dynamic binding. They are as follows:

1. Static binding occurs at compile-time while dynamic binding occurs at runtime.

2. In static binding, actual object is not used whereas, actual object is used in the dynamic binding.

3. Static binding is resolved at compile time whereas, dynamic binding is resolved at runtime.

4. Static binding is also called late binding because it happens during compilation whereas, dynamic binding is called early binding because it happens during runtime.

5. An example of static binding is method overloading whereas, the example of dynamic binding is method overriding.

6. Private, static, and final methods show static binding because they cannot be overridden whereas, except private, static, and final methods, other methods show dynamic binding because they can be overridden.


Hope that this tutorial has covered almost all the important points related to static and dynamic binding in java with many example programs. I hope that you will have understood this easy topic and enjoyed it.
Thanks for reading!!!
Next ⇒ Exception Handling in Java

Polymorphism in Java | Compile Time, Runtime, Example

 Polymorphism in java is one of the core concepts of object-oriented programming language (OOPs).

The word polymorphism is derived from two Greek words: poly and morphs. The word “poly” implies many and “morphs” means forms.

Therefore, polymorphism means “many forms”. That is one thing that can take many forms.

Polymorphism is a concept by which we can perform a single task in different ways. That is, when a single entity behaves differently in different cases, it is called polymorphism in Java.

We can achieve flexibility in our code using polymorphism because we can perform various operations by using methods with the same names according to requirements.

Let’s understand it with some realtime examples.

Realtime Example of Polymorphism in Java


There are several real-time examples of polymorphism in the world.

Polymorphism in Java
1. We all know that water is a liquid, but it changes to solid when it frozen, and it changes to a gas when it is heated at its boiling point.

2. The best example of polymorphism is human behavior. One person can have different behavior. For example, a person acts as an employee in the office, a customer in the shopping mall, a passenger in bus/train, a student in school, and a son at home.

3. We all use a single button to switch ON and OFF the computer.

4. A boy starts his love by saying the word “friendship” but the girl ends that love with the same word “friendship”. The girl says that we will be always good friends.

Here, the word “friendship” is the same but attitude is different. This beautiful concept is nothing but polymorphism.

Types of Polymorphism in Java


Basically, there are two types of polymorphism in java. They are:

1. Static polymorphism
2. Dynamic polymorphism

Types of polymorphism in Java
Polymorphism can be either static or dynamic depending on how the method is called in a class.

Static Polymorphism in Java


A polymorphism that exhibited during compilation is called static polymorphism in java. In static polymorphism, the behavior of a method is decided at compile-time.

Hence, Java compiler binds method calls with method definition/body during compilation. Therefore, this type of polymorphism is also called compile-time polymorphism in Java.

Since binding is performed at compile-time, it is also known as early binding. Compile-time polymorphism can be achieved/implemented by method overloading in java.

Method overloading is a mechanism in which a class has multiple methods having the same name but different signatures. It is one of the ways that Java implements polymorphism.

Another example of static polymorphism is constructor overloading and method hiding.

Java Compile-time Polymorphism Example Program


Let’s take an example program where we will implement static polymorphism. In this example program, we will create a class StaticPoly.

In this class, we will create two methods having the same name sum. Both of these methods will have different signatures. Let’s start coding.

Program source code 1:

package staticPolymorphism; 
public class StaticPoly 
{ 
  void sum(int x, int y) 
  { 
    int s = x + y; 
    System.out.println("Sum of two numbers: " +s); 
  } 
void sum(int x, int y, int z) 
{ 
   int s = x + y + z; 
   System.out.println("Sum of three numbers: " +s); 
  } 
public static void main(String[] args) 
{ 
  StaticPoly obj = new StaticPoly(); 
   obj.sum(20, 10); 
   obj.sum(10, 20, 30); 
  } 
}
Output: 
       Sum of two numbers: 30 
       Sum of three numbers: 60

Explanation:

As you can observe in the preceding example program, the sum() method is overloaded two times because both methods’ signatures vary in the number of parameters.

The first sum() method accepts two parameters whereas, the second sum() method accepts three parameters.

When we will call the first sum() method using reference variable “obj” by passing two int type argument values, Java compiler binds the definition of sum(int x, int y) method with sum(20, 10) method during compilation and calls the appropriate method.

Hence, the sum of two numbers is displayed by invoking sum() method on the console.

Similarly, when we call the second sum() method by passing three int type argument values, Java compiler binds the definition of sum(int x, int y, int z) with sum(10, 20, 30) method during compilation, and calls a method of the sum of three numbers.

Thus, Java compiler matches the values passed to a method during compilation, binds method call with appropriate method definition, and calls the appropriate method.

In this way, compile-time polymorphism allows us to perform various operations by using multiple methods with the same name.

Key point:

Java compiler differentiates multiple methods having the same name by their signatures.

Dynamic Polymorphism in Java


A polymorphism that is exhibited at runtime is called dynamic polymorphism in java. In dynamic polymorphism, the behavior of a method is decided at runtime,

therefore, the JVM (Java Virtual Machine) binds the method call with method definition/body at runtime and invokes the relevant method during runtime when the method is called.

This happens because objects are created at runtime and the method is called using an object of the class. The Java compiler has no awareness of the method to be called on an instance during compilation. Therefore, JVM invokes the relevant method during runtime.

Dynamic or runtime polymorphism can be achieved/implemented in java using method overriding. Method overriding is a mechanism where a method of Base class is overridden in the derived class to provide a more specific implementation.

The signature of method in both base and derived classes is the same but they only differ in their implementation.

Let’s take an example program where we will implement dynamic polymorphism by method overriding.

Java Runtime Polymorphism Example Program


Let us consider two classes Base and Derived, as shown in the below code snippet. In both classes, we will declare a method named “calc” having the same signature.

Program source code 2:

package dynamicPoly; 
public class Base 
{ 
  void m1() 
  { 
    System.out.println("m1-Base"); 
  } 
} 
public class Derived extends Base 
{ 
  void m1() 
  { 
    System.out.println("m1-Derived"); 
  } 
} 
public class DynamicPoly 
{ 
  public static void main(String [] args) 
  { 
     Derived d = new Derived(); 
      d.m1(); // Calling m1() method of class Derived. 
    
    Base b = new Base(); 
       b.m1(); // Calling m1() method of class Base. 
   } 
 }
Output: 
       m1-Derived 
       m1-Base

As you can observe in the above program, the class Base contains a method named m1. This m1() method is overridden in the derived class named Derived.

Since m1() method in both Base and Derived classes have the same name and signature, therefore, the Java compiler is unable to bind method calls with method definitions.

Hence, based on an object of a class, JVM decides to execute a suitable method at runtime. In this way, method overriding is one way to implement runtime polymorphism in java.

For a more detailed explanation of method overriding, go to this tutorial: Method overriding in Java

Programming in Java (Semester-5)

  Programming in Java (Semester-5) Syllabus Unit I Unit II Unit III Practical Question Bank Java Practical Programs Java Important Topics Qu...