DEV Community

Divya Divya
Divya Divya

Posted on

Abstract in Java?

Java Abstract Class

  • An abstract class in Java is a class declared with the abstract keyword.
  • It is used to achieve abstraction, which means hiding implementation details and showing only essential functionality.

Key Features of Abstract Class

  • Cannot create objects directly
  • Can contain abstract methods and normal methods
  • Must be inherited by another class
  • Used as a base class

Syntax

abstract class ClassName {

}
Enter fullscreen mode Exit fullscreen mode

Main Method

Car c = new Car();
Enter fullscreen mode Exit fullscreen mode

Creates object for child class, not abstract class.

Important point

Vehicle v = new Vehicle();
Enter fullscreen mode Exit fullscreen mode

Because abstract class objects cannot be created.

Abstract Method in Java

  • An abstract method is a method declared without a body.
  • It contains only the method declaration, and the implementation is provided by the subclass.

Syntax

abstract void sound();
Enter fullscreen mode Exit fullscreen mode
  • No method body
  • Ends with semicolon ;

Important points:

  • Abstract methods can only be inside an abstract class
  • Child class must implement the abstract method
  • Used to achieve abstraction.

Rule

If a class contains an abstract method, the class must be abstract.

abstract class Animal {

    abstract void sound();
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)