How to ensure that child class overrides a super class method in java?

Java 8Object Oriented ProgrammingProgramming

A method which does not have body is known as abstract method. It contains only method signature with a semi colon and, an abstract keyword before it.

public abstract myMethod();

To use an abstract method, you need to inherit it by extending its class and provide implementation (body) to it. If a class contains at least one abstract method, you must declare it abstract.

In other words, if you extend an abstract class it is mandatory to implement (override) all the abstract methods in it or, declare it abstract else a compile time error will be generated for each abstract method (that you don’t override) saying “subclass_name is not abstract and does not override abstract method abstractmethod_name in classname”.

Example

Following Java example contains two abstract classes: One is an abstract class (MyClass) that contains 3 abstract methods and the other is a class with name AbstractClassExample that extends the earlier one.

In the subclass we are overriding only one abstract method (display()).

import java.io.IOException;
abstract class MyClass {
   public abstract void display();
   public abstract void setName(String name);
   public abstract void setAge(int age);
}
public class AbstractClassExample extends MyClass{
   public void display(){
      System.out.println("subclass implementation of the display method ");
   }
   public static void main(String args[]) {
      new AbstractClassExample().display();
   }
}

Compile time error

On compiling, the above method generates the following compile time error.

AbstractClassExample.java:9: error: AbstractClassExample is not abstract and does not override abstract method setAge(int) in MyClass
public class AbstractClassExample extends MyClass{
^
1 error

Therefore, if you need to make sure that the sub class overrides a particular method of the super class method, you just need to declare the required method abstract.

To make the above program work you need to implement all the abstract methods as −

Example

abstract class MyClass {
   public abstract void display();
   public abstract void setName(String name);
   public abstract void setAge(int age);
}
public class AbstractClassExample extends MyClass{
   public void display(){
      System.out.println("subclass implementation of the display method ");
   }
   public void setName(String name){
      System.out.println("Name: "+name);
   }
   public void setAge(int age){
      System.out.println("Age: "+age);
   }
   public static void main(String args[]) {
      AbstractClassExample obj = new AbstractClassExample();
      obj.display();
      obj.setName("Krishna");
      obj.setAge(20);
   }
}

Output

subclass implementation of the display method
Name: Krishna
Age: 20
raja
Published on 01-Aug-2019 11:55:07
Advertisements