Java abstract method example | Use non-abstract class

A Java method without body statement means the only declaration and does not have an implementation called a Java abstract method. The abstract method must start to be used as an Abstract keyword. An Abstract method can use only in Abstract class.

Java abstract method example

Syntax

A simple syntax (signature) of Abstract method.

Java abstract method example

Let’s see an example of it. Where a regular class extends the Abstract class and implement all Abstract methods.

You can see in Abstract class there only mentioned method name without any implementation.

Output: 6
14

Rules of Abstract Method

Some point you should remember when making Abstract Methods.

  • Abstract method should be no body. Means no curly braces and statement.
  • It should be declared with abstract keyword.
  • If any regular class extends the Abstract class, then the class must have to implement all the abstract methods. Else it has to be declared abstract as well.

Q: Is it possible to Java abstract method in non-abstract class?

Answer: You can not. It is not possible. The Java compiler will refuse to compile a non-abstract class, which includes, or inherits, any method declared as abstract.

if even one method in the class or all methods inherited from superclasses is abstract, then still class must be declared abstract.

Q: What is the use of the abstract method in Java?

Answer: It forces any non-abstract class that inherits from it to must implement the method, similar to an interface.

For example:
You want your subclasses to have a method disp() but at the same time, you want it to be different for each class. Then you declare this method abstract in the parent class. So all the subclasses will have to implement this method and give their own implementation.

Q: Can we override abstract method in java?

Answer: Tricky question in interview.

Yes, And it must be overridden. The whole concept of it based on only it – Read this tutorial( What is Overriding in Java?)

Do comment if you have any doubt and suggestion on this tutorial.

Note: This example (Project) is developed in IntelliJ IDEA 2018.2.6 (Community Edition)
JRE: 11.0.1
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.14.1
Java version 11
All Abstract method in java Examples are in Java 11, so it may change on different from Java 9 or 10 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.