What is Method Overriding

Method Overriding happens when a method in a subclass has the same name and type signature as a method in its superclass.

When an overridden method is called within a subclass, it will refer to the method defined in the subclass.

The method defined by the superclass will be hidden.

Consider the following:

 
class Base {
  int i;
  Base(int a) {
    i = a;
  }
  void show() {
    System.out.println("i:" + i);
  }
}
class SubClass extends Base {
  int k;
  SubClass(int a, int c) {
    super(a);
    k = c;
  }
  void show() {
    System.out.println("k: " + k);
  }
}
public class Main {
  public static void main(String args[]) {
    SubClass subOb = new SubClass(1, 3);
    subOb.show();
  }
}

The output produced by this program is shown here:


k: 3
Home 
  Java Book 
    Class  

Inheritance:
  1. Inheritance Basics
  2. When Constructors Are Called
  3. Using super keyword
  4. What is Method Overriding
  5. super and overridden method
  6. Method overriding vs method overload
  7. Dynamic Method Dispatch
  8. final variables