Method Overloading
deals with the notion of having two or more methods in the same class with the same name but different arguments.
1 | static int binarySearch( byte [] a, byte key); |
2 | static 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.
02 | protected int legs = 1 ; |
07 | class Bird extends Animal{ |
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 意見:
張貼留言