Wednesday, February 19

Overloading vs Overriding in Java

Overloading and overriding are completely different. Only the notion about interface (function) name is same. Overloading is the ability to use same interface name but with different arguments. Purpose of functions might be same but the way they work will differ based on the argument types. Overriding is applicable in the context of inheritance. When there is a need to change the behavior of a particular inherited method, it will be overridden in the sub-class.



How to overload methods ?


public class ExOverloading{
private String name = null;
public ExOverloading(){
this.name = "default";
}
public ExOverloading(String name){
this.name = name;
}
public String displayInfo(){
return "The Name is "+this.name;
}
public String displayInfo(int age){
return "The Name is "+this.name+" and age is "+age+" yrs";
}
public static void main(String... args){
ExOverloading obj1 = new ExOverloading();
System.out.prinln(obj1.displayInfo());//The Name is default
System.out.prinln(obj1.displayInfo(5));//The Name is default and age is 5 yrs
ExOverloading obj2 = new ExOverloading("Jon Doe");
System.out.prinln(obj2.displayInfo());//The Name is Jon Doe.
System.out.prinln(obj2.displayInfo(12));//The Name is Jon Doe and age is 12 yrs.
}
}


How to override methods ?


class Bird{
public void info(){
System.out.println("Bird Can fly");
}
}
class Kiwi extends Bird{
public void info(){
System.out.println("Kiwi Can't fly");
}
}
public class ExOverriding{
public static void main(String args[]){
Bird bird = new Bird();
Bird kiwi = new Kiwi();
bird.info();//Bird Can fly
kiwi.info();//Kiwi Can't fly
}
}

No comments:

Post a Comment

Ads Inside Post