Tutorialspoint

1 Answer
Jai Janardhan

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

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.