Java also support function Overloading and function overriding:
- Overloading
- have the same function name
- exit in the same class
- difference signature (type or number parameter)
- allow more than definition for a function name
Example :
// www.learning2night.com public class SumData { static int sum(int a,int b){ return a+b; } static float sum(float a, float b){ return a+b; } static double sum(double a, double b){ return a+b; } public static void main(String[] args) { System.out.println("Sum int :"+sum(1,2)); System.out.println("float int :"+sum(1.0,2.0)); System.out.println("double int :"+sum(1.0D,2.0D)); } }
Output:
Sum int :3 float int :3.0 double int :3.0
- Overriding
- have the same function name and signature
- exit in inheritance
- must be done in class
- child class override function of parent(s) class
Example:
public class Person { private String fname; public String lname; public Person(String fname, String lname) { this.fname = fname; this.lname = lname; } public String getFname() { return fname; } public void setFname(String fname) { this.fname = fname; } @Override public String toString() { return "fname=" + this.fname + ", lname=" + this.lname ; } public void display(){ System.out.print("display in super class"); } }
public class Student extends Person { private double salary; public Student(String fname, String lname) { super(fname, lname);// call super class constructor System.out.println("this sub class Constructor "); } public Student(String fname, String lname, double salary) { super(fname, lname);// call super class constructor this.salary = salary; } // override method @Override public String toString() { // super.toString() invoke super class method return super.toString()+"salary=" + this.salary ; } // override method public void display() { System.out.println("display in child class"); } }
public class Test { public static void main(String[] args) { Student st = new Student("Learning","Tonight",100); st.display(); } }
Output:
display in child class