Javatpoint Logo
Javatpoint Logo

Java abstract Keyword

The abstract keyword is used to achieve abstraction in Java. It is a non-access modifier which is used to create abstract class and method.

The role of an abstract class is to contain abstract methods. However, it may also contain non-abstract methods. The method which is declared with abstract keyword and doesn't have any implementation is known as an abstract method.

Syntax:-

Note - We cannot declare abstract methods in non abstract class.

Rules of abstract keyword

Don'ts

  • An abstract keyword cannot be used with variables and constructors.
  • If a class is abstract, it cannot be instantiated.
  • If a method is abstract, it doesn't contain the body.
  • We cannot use the abstract keyword with the final.
  • We cannot declare abstract methods as private.
  • We cannot declare abstract methods as static.
  • An abstract method can't be synchronized.

Do's

  • An abstract keyword can only be used with class and method.
  • An abstract class can contain constructors and static methods.
  • If a class extends the abstract class, it must also implement at least one of the abstract method.
  • An abstract class can contain the main method and the final method.
  • An abstract class can contain overloaded abstract methods.
  • We can declare the local inner class as abstract.
  • We can declare the abstract method with a throw clause.

Examples of abstract Keyword

Example 1: Abstract class containing the abstract method

Test it Now

Output:

Bike is running

Example 2: Abstract class containing the abstract and non-abstract method

Test it Now

Output:

Bike is running
Car is running

Example 3: Abstract class containing the constructor

Test it Now

Output:

Constructor is invoked

Example 4: Abstract class containing overloaded abstract methods

Test it Now

Output:

abstract method is invoked
overloaded abstract method is invoked

Example 5: Inner abstract class

Test it Now

Output:

inner abstract class is invoked

Example 6: Nested abstract class

Test it Now

Output:

nested abstract class is invoked




Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA