Doing something you intrinsically are enthusiastic with.

2016年8月8日 星期一

Difference between overriding and overloading in Java

凌晨3:16 Posted by Unknown No comments

Method Overloading

deals with the notion of having two or more methods in the same class with the same name but different arguments.


1static int binarySearch(byte[] a, byte key);
2static int binarySearch(byte[] a, int fromIndex, int toIndex, byte key)  


Method Overriding

means having two methods with the same arguments, but different implementations. One of them would exist in the parent class, while another will be in the derived, or child class. 


01class Animal{
02    protected int legs = 1;
03    public int getLegs(){
04      return legs*4;
05    }
06}
07class Bird extends Animal{
08   public int getLegs(){
09       return legs*2;
10   }
11}


Also the dynamic binding and static binding issues are related to this topic

Look at the examples below

We overload the eat method

public class Animal{}


public class Dog extends Animal{}

public class AnimalActivity{

    public void eat(Animal a){
       System.out.println("Animal is eating");
    }

    public void eat(Dog d){
       System.out.println("Dog is eating");
    }
}
then in the main class:
public static void main(String args[])
{
    Animal a=new Animal();
    Animal d=new Dog();
    AnimalActivity aa=new AnimalActivity();
    aa.eat(a);
    aa.eat(d);
}
the result in both two cases will be: Animal is eating
Then we try to override the eat mehod of Animal class
public class Animal{
    public void eat(){
System.out.println("Animal is eating");
}
}
then:
public Class Dog extends Animal{
public void eat(){
    System.out.println("Dog is eating");
    }
}
then in the main class:
public static void main(String args[]){
Animal d=new Dog();
Animal a=new Animal();
a.eat();
d.eat();
}
now the result should be:
Animal is eating
Dog is eating
So we can conclude here
Overloading binds at compile time "static binding"  while
Overriding binds at run time "dynamic binding"






0 意見:

張貼留言