Java Method Overriding

In this chapter you will learn:

  1. How to override a method from parent class
  2. Example - Java Method Overriding
  3. How to use super to access the overridden method
  4. When to overload method and when to override method

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 {//from  w  w  w.  ja  v a  2s  .com
  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 {/*from   w  w w.ja v  a2  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 {//www .j  a v a  2 s  .  com
  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:

Next chapter...

What you will learn in the next chapter:

  1. Java Constructor in hierarchy
  2. When constructors are called when invoking a subclass