What happens if the subclass does not override abstract methods 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 to it.

A class which contains 0 or more abstract methods is known as abstract class. If it contains at least one abstract method, it must be declared abstract.

Extending an abstract class

Once you extend an abstract class in Java you need to override all the abstractmethods in it or, declare it abstract. If you don’t, 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()).

 Live Demo

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("This is the 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

Output

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

To make this program work you either need to override all the abstract methods of the super-class or, make the subclass abstract as shown below −

abstract class MyClass {
   public abstract void display();
   public abstract void setName(String name);
   public abstract void setAge(int age);
}
public abstract class AbstractClassExample extends MyClass{
   public void display(){
      System.out.println("This is the subclass implementation of the displaymethod ");
   }
}
raja
Published on 04-Jul-2019 17:17:31
Advertisements