In java two types of binding is available.
1. Static Binding
2. Dynamic Binding
Before seeing the code example remembering below points may help you to understand easily.
1. Static binding in java will occur at compile time only. It also known as early binding.
2. Dynamic binding in java will occur at run time only. It also known late binding.
3. Static binding will happen through method overloading only.
4. Dynamic binding will happen through method overriding only. So obviously class needs to be extended.
Example of Static Binding
public class StaticBindingTest { public static void main(String args[]) { List myList = new ArrayList(); StaticBindingTest obj = new StaticBindingTest(); obj.test(myList); } public Collection test(List c){ System.out.println("Inside List test method"); return c; } public Collection test(ArrayList as){ System.out.println("Inside ArrayList test method"); return as; } }
Output:
Inside List test method
The compiler will decide which method needs to be executed at compile time itself. See below image
As we discussed earlier its happening through overloading. Compiler decided List myList to be passed to test method. So its printing above output. Its not listening new Arraylist. Hope you understand.
After seeing the example Dynamic binding you will understand 100% clearly about both static and dynamic.
Example of Dynamic Binding
public class DynamicBindingTest { public static void main(String args[]) { Vehicle vehicle = new Car(); //Vehicle is super class and Car is a sub class vehicle.test(); } } class Vehicle { public void test() { System.out.println("Inside test method of Vehicle"); } } class Car extends Vehicle { @Override public void test() { System.out.println("Inside test method of Car"); } }
Output: Inside test method of Car
Vehicle is a super class and car is a sub class. As per rule, super class can hold sub class. So that added code like Vehicle vehicle = new Car(); See, we used here overriding. So dynamic binding.
below image will tell more,
Run time it will check sub class of Car and calling test method of Car class. Still confusing, simply remember compile time left side and run time right side.
No comments:
Post a Comment