Overriding and overloading in Java with examples
Here are some important facts:
1. Object type (not the reference variable’s type), determines which overridden method is used at runtime.
2. Reference type determines which overloaded method will be used at compile time.
3. Polymorphism applies to overriding, not to overloading.
Here is an example of overridding. After reading the code, guess the output. Easy!
class Dog{ public void bark(){ System.out.println("woof "); } } class Hound extends Dog{ public void sniff(){ System.out.println("sniff "); } public void bark(){ System.out.println("bowl"); } } public class Main { public static void main(String [] args){ new Main().go(); } void go(){ new Hound().bark(); ((Dog) new Hound()).bark(); //((Dog) new Hound()).sniff(); } }
Output?
Yes, here you go.
bowl bowl
A better example:
class Animal { void stinky(){ System.out.println("stinky animal !"); } } class Dog extends Animal{ public void stinky() { System.out.println("stinky dog !"); } public void bark(){ System.out.println("wow wow"); } } class Cow extends Animal{ public void stinky() { System.out.println("stinky cow !"); }
when you create object like this and call a method:
Animal obj = new Dog();
obj.stinky();
What compiler does is, it check the class type of obj which is Animal. After that it checks whether the stinky() exist in Animal or not. Always remember that objects are created at runtime. So complier has no way to determine that the Dog class stinky() method is to be called. So at compile time class type of reference variable is checked to check such a method exist or not.
Now at run time the jvm knows that though the class type of obj is Animal but at run time it is referring to the object of Dog. So it calls the stinky() of Dog class. This is called Dynamic Polymorphism.
You may also like:
Leave a comment