What is method overriding for Java language

Syntax for 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.

Example

The method defined by the superclass will be hidden. Consider the following:

 
class Base {/* w w w . j  a va  2 s .co m*/
  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:

super and overridden method

To access the superclass version of an overridden function, you can do so by using super.

 
class Base {/*  www.j  a va 2 s  .c o m*/
  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() {
    super.show(); // this calls A's show()
    System.out.println("k: " + k);

  }
}

public class Main {
  public static void main(String[] argv) {
    SubClass sub = new SubClass(1, 2);
    sub.show();
  }
}

The following output will be generated if you run the code above:

Method overriding vs method overload

Method overriding occurs when the names and the type signatures of the two methods are identical. If not, the two methods are overloaded. For example, consider this modified version of the preceding example:

 
class Base {/*from  w  ww  . j  a va  2 s  .  c  om*/
  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(String msg) {
    System.out.println(msg + k);
  }
}
public class Main {
  public static void main(String args[]) {
    SubClass subOb = new SubClass(1, 2);
    subOb.show("This is k: "); 
    subOb.show(); 
  }
}

The output produced by this program is shown here:





















Home »
  Java Tutorial »
    Java Language »




Java Data Type, Operator
Java Statement
Java Class
Java Array
Java Exception Handling
Java Annotations
Java Generics
Java Data Structures