The abstract keyword is used for classes and methods in Java. It is not an access modifier, but it is used to achieve abstraction in Java.
abstract class: An abstract class does not allow you to create an object of it. To access the methods and variables of this class, you must inherit this class.
abstract method: An abstract method is a method without body, you can declare it inside abstract class only. The body is defined by the sub class using the method overriding feature.
Abstract class and method Example
In this example, we have an abstract class MyAbsClass
and this class contains an abstract method msg()
. Another class JavaExample
extends this class, this class has to override the abstract method of parent class, else it has to be declared abstract as well.
// abstract class abstract class MyAbsClass { public String webName = "BeginnersBook.com"; public int webAge = 12; public abstract void msg(); // abstract method } // Subclass: Inheriting abstract class "MyAbsClass" class JavaExample extends MyAbsClass { // Overriding the msg() method here and providing the body public void msg() { System.out.println("Happy Learning!"); } public static void main(String args[]){ JavaExample obj = new JavaExample(); System.out.println("Website Name: " + obj.webName); System.out.println("Website age: " + obj.webAge); obj.msg(); } }
Output:
Website Name: BeginnersBook.com Website age: 12 Happy Learning!
Points to remember:
- An abstract method can only be declared inside abstract class.
- A class extending abstract class must have to override the abstract method or it should be declared abstract.
- You cannot create an object of abstract class.
- An abstract method cannot be declared static, final or private.