Java method Overriding

Below example illustrates method Overriding in java. Method overriding in java means a subclass method overriding a super class method. Superclass method should be non-static.

Java method Overriding

     

Below example illustrates method Overriding in java. Method overriding in java means a subclass method overriding a super class method. Superclass method should be non-static. Subclass uses extends keyword to extend the super class. In the example class B is is the sub class and class A is the super class. In overriding methods of both subclass and superclass possess same signatures. Overriding is used in modifying  the methods of the super class. In overriding  return types and constructor parameters of methods should match .

 

 

 

 

Here is the code:

class A {
int i;
A(int a, int b) {
i = a+b;
}
void add() {
System.out.println("Sum of a and b is: " + i);
}
}
class B extends A {
int j;
B(int a, int b, int c) {
super(a, b);
j = a+b+c;
}
void add() {
super.add();
System.out.println("Sum of a, b and c is: " + j);
}
}
class MethodOverriding {
public static void main(String args[]) {
B b = new B(10, 20, 30);
b.add();
}
}

Output will be displayed as:

Download Source Code