When Method Overriding occurs in Java?


Method overriding occurs in Java if the child class has the same method as that declared in the parent class. The method in the child class has the same name and parameters as that of the method in the parent class. Method overriding is useful in runtime polymorphism.

A program that demonstrates this is given as follows:

Example

 Live Demo

class A {
   int a;
   A(int x) {
      a = x;
   }
   void print() {
      System.out.println("Value of a: " + a);
   }
}
class B extends A {
   int b;
   B(int x, int y) {
      super(x);
      b = y;
   }
   void print() {
      System.out.println("Value of b: " + b);
   }
}
public class Demo {
   public static void main(String args[]) {
      B obj = new B(4, 9);
      obj.print();
   }
}

Output

Value of b: 9
raja
Published on 12-Feb-2019 15:45:39
Advertisements