InterviewSolution
Saved Bookmarks
| 1. |
Static vs Dynamic Binding in Java |
|
Answer» Static binding can be resolved at the compile time by the COMPILER. All the static, final and private method binding is DONE at compile time. Another word for static binding is EARLY binding. An example of static binding is given as follows: public class Demo { public static class ANIMAL { static VOID display() { System.out.println("This is an Animal"); } } public static class Mammal extends Animal { static void display() { System.out.println("This is a Mammal"); } } public static void main(String[] args) { Animal obj1 = new Animal(); Mammal obj2 = new Mammal(); obj1.display(); obj2.display(); } }The output of the above program is as follows: This is an Animal This is a MammalIn dynamic binding, the type of the object is determined at run time. One of the examples of dynamic binding is overriding. An example of dynamic binding is given as follows: public class Demo { public static class Animal { void display() { System.out.println("This is an Animal"); } } public static class Mammal extends Animal { @Override void display() { System.out.println("This is a Mammal"); } } public static void main(String[] args) { Animal obj1 = new Animal(); Animal obj2 = new Mammal(); obj1.display(); obj2.display(); } }The output of the above program is as follows: This is an Animal This is a Mammal |
|