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

Updated on: 30-Jul-2019

242 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements