Java Method Overriding

Introduction

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

The method in the subclass is said to override the method in the superclass.

When an overridden method is called from its subclass, it refers to the method defined by the subclass.

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

// Method overriding.
class A {/*from   ww w.j  a  v  a 2  s .  c o m*/
  int i, j;

  A(int a, int b) {
    i = a;
    j = b;
  }

  // display i and j
  void show() {
    System.out.println("i and j: " + i + " " + j);
  }
}

class B extends A {
  int k;

  B(int a, int b, int c) {
    super(a, b);
    k = c;
  }

  // display k -- this overrides show() in A
  void show() {
    System.out.println("k: " + k);
  }
}
  
public class Main {
  public static void main(String args[]) {
    B subOb = new B(1, 2, 3);

    subOb.show(); // this calls show() in B
  }
}



PreviousNext

Related