
Difference between overloading and overriding.It is very important to understand the difference between these to concept.
Property | Overloading | Overriding |
method name | must be same | must be same |
argument types | must be different (atleast order) | must be same |
method signautre | must be different | must be same |
return types | no restriction | must be same util 1.4V ,from 1.5 onward CO-Variant return types are allowed. |
private , static and final methods | can be overloaded | can not be overridden |
access modifier | no restriction | the scope of access modifier can not be reduced but can be increased. |
throws clause | no ristriction | If a child method class method throws any checked exception then compulsory parent class method should throws same checked exception or its parent type. |
method body resolution | at compile time | at run time |
They are also known as | CompileTime polymorphism/Static Binding/ Early Binding | RunTime polymorphism/Dynamic Binding/ Late Binding |
//example of method overloading
class Example {
// sum of 2 int type argument
public void sum(int a, int b) {
System.out.println("sum =" + (a + b));
}
// sum of 2 double type argument
public void sum(double a, double b) {
System.out.println("sum =" + (a + b));
}
// sum of 2 float type value
public void sum(float a, float b) {
System.out.println("sum =" + (a + b));
}
//main method
public static void main(String[] args) {
Example ex = new Example();
ex.sum(2, 3);
ex.sum(1.2, 1.6);
ex.sum(2f, 3f);// using floating literal
}
}
sum =5 sum =2.8 sum =5.0
// example of method overriding
class A {
int i, j;
A(int a, int b) {
i = a;
j = b;
}
// print i and j
void display() {
System.out.println("value of i =" + i);
System.out.println("value of j =" + j);
}
}
class B extends A {
int p;
B(int a, int b, int c) {
super(a, b);
p = c;
}
// print p
// this method overrides display() of Parent class(A)
void display() {
System.out.println("value of p= " + p);
}
}
public class Example {
public static void main(String[] args) {
B b = new B(2, 4, 5);
b.display();// this class display() of B
}
}
value of p= 5