In this post I will show you another interesting example of Java Dynamic Binding…

Did you expect such behavior? Feel free to comment. Thanks.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
package staticbinder; class Animal { static void talk() { System.out.println("Animal doesen't talk!!"); } void eat() { System.out.println("Animal eating..."); } } class Dog extends Animal { static void talk() { System.out.println("Dog barking..."); } @Override void eat() { System.out.println("Dog eating..."); } } public class Main { public static void main(String[] args) { Animal a = new Dog(); /* static binding happens in private, final, static and * overloaded methods at compile time */ a.talk(); // will print: Animal doesen't talk!! /* dynamic binding happens in overriding methods at * run time */ a.eat(); // will print: Dog eating... } } |