close
The Wayback Machine - https://web.archive.org/web/20230512155242/https://www.geeksforgeeks.org/abstract-keyword-in-java/
Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

abstract keyword in java

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

abstract is a non-access modifier in java applicable for classes, methods but not variables. It is used to achieve abstraction which is one of the pillar of Object Oriented Programming(OOP). Following are different contexts where abstract can be used in Java.
 

Charactertics of abstract keyword :

In Java, the abstract keyword is used to define abstract classes and methods. Here are some of its key characteristics:

  • Abstract classes cannot be instantiated: An abstract class is a class that cannot be instantiated directly. Instead, it is meant to be extended by other classes, which can provide concrete implementations of its abstract methods.
  • Abstract methods do not have a body: An abstract method is a method that does not have an implementation. It is declared using the abstract keyword and ends with a semicolon instead of a method body. Subclasses of an abstract class must provide a concrete implementation of all abstract methods defined in the parent class.
  • Abstract classes can have both abstract and concrete methods: Abstract classes can contain both abstract and concrete methods. Concrete methods are implemented in the abstract class itself and can be used by both the abstract class and its subclasses.
  • Abstract classes can have constructors: Abstract classes can have constructors, which are used to initialize instance variables and perform other initialization tasks. However, because abstract classes cannot be instantiated directly, their constructors are typically called by constructors in concrete subclasses.
  • Abstract classes can contain instance variables: Abstract classes can contain instance variables, which can be used by both the abstract class and its subclasses. Subclasses can access these variables directly, just like any other instance variables.
  • Abstract classes can implement interfaces: Abstract classes can implement interfaces, which define a set of methods that must be implemented by any class that implements the interface. In this case, the abstract class must provide concrete implementations of all methods defined in the interface.

Overall, the abstract keyword is a powerful tool for defining abstract classes and methods in Java. By declaring a class or method as abstract, developers can provide a structure for subclassing and ensure that certain methods are implemented in a consistent way across all subclasses.

Abstract classes

The class which is having partial implementation(i.e. not all methods present in the class have method definition). To declare a class abstract, use this general form : 
 

abstract class class-name{
    //body of class
}

Due to their partial implementation, we cannot instantiate abstract classes.Any subclass of an abstract class must either implement all of the abstract methods in the super-class, or be declared abstract itself.Some of the predefined classes in java are abstract. They depend on their sub-classes to provide complete implementation. For example, java.lang.Number is a abstract class. For more on abstract classes, see abstract classes in java
 

Abstract methods

Sometimes, we require just method declaration in super-classes.This can be achieve by specifying the abstract type modifier. These methods are sometimes referred to as subclasser responsibility because they have no implementation specified in the super-class. Thus, a subclass must override them to provide method definition. To declare an abstract method, use this general form: 
 

abstract type method-name(parameter-list);

As you can see, no method body is present.Any concrete class(i.e. class without abstract keyword) that extends an abstract class must overrides all the abstract methods of the class.
Important rules for abstract methods: 
 

  • Any class that contains one or more abstract methods must also be declared abstract
  • The following are various illegal combinations of other modifiers for methods with respect to abstract modifier : 
    1. final
    2. abstract native
    3. abstract synchronized
    4. abstract static
    5. abstract private
    6. abstract strictfp

Simple Example of abstract class to understand the abstract keyword : 

Java




abstract class gfg {
    abstract void printInfo();
}
 
class employee extends gfg {
    void printInfo() {
        String name = "aakanksha";
        int age = 21;
        float salary = 55552.2F;
 
        System.out.println(name);
        System.out.println(age);
        System.out.println(salary);
 
    }
 
}
 
class base {
    public static void main(String args[]) {
        gfg s = new employee();
        s.printInfo();
    }
}

Output

aakanksha
21
55552.2

Consider the following java program, that illustrate the use of abstract keyword with classes and methods. 
 

Java




// A java program to demonstrate
// use of abstract keyword.
 
// abstract with class
abstract class A
{
    // abstract with method
    // it has no body
    abstract void m1();
     
    // concrete methods are still allowed in abstract classes
    void m2()
    {
        System.out.println("This is a concrete method.");
    }
}
 
// concrete class B
class B extends A
{
    // class B must override m1() method
    // otherwise, compile-time exception will be thrown
    void m1() {
        System.out.println("B's implementation of m1.");
    }
     
     
}
 
// Driver class
public class AbstractDemo
{
    public static void main(String args[])
    {
        B b = new B();
        b.m1();
        b.m2();
    }
}

Output

B's implementation of m1.
This is a concrete method.

Example:

Java




// Define an abstract class
abstract class Shape {
  // Define an abstract method
  public abstract double getArea();
}
 
// Define a concrete subclass of Shape
class Circle extends Shape {
  private double radius;
 
  public Circle(double radius) {
    this.radius = radius;
  }
 
  public double getArea() {
    return Math.PI * radius * radius;
  }
}
 
// Define another concrete subclass of Shape
class Rectangle extends Shape {
  private double width;
  private double height;
 
  public Rectangle(double width, double height) {
    this.width = width;
    this.height = height;
  }
 
  public double getArea() {
    return width * height;
  }
}
 
// Use the Shape class and its subclasses
public class Main {
  public static void main(String[] args) {
    Circle circle = new Circle(5);
    Rectangle rectangle = new Rectangle(10, 20);
 
    System.out.println("Circle area: " + circle.getArea());
    System.out.println("Rectangle area: " + rectangle.getArea());
  }
}

Output

Circle area: 78.53981633974483
Rectangle area: 200.0

Note : Although abstract classes cannot be used to instantiate objects, they can be used to create object references, because Java’s approach to run-time polymorphism is implemented through the use of super-class references. Thus, it must be possible to create a reference to an abstract class so that it can be used to point to a subclass object.
 

Advantages:

Here are some advantages of using the abstract keyword in Java:

  • Provides a way to define a common interface: Abstract classes can define a common interface that can be used by all subclasses. By defining common methods and properties, abstract classes provide a way to enforce consistency and maintainability across an application.
  • Enables polymorphism: By defining a superclass as abstract, you can create a collection of subclasses that can be treated as instances of the superclass. This allows for greater flexibility and extensibility in your code, as you can add new subclasses without changing the code that uses them.
  • Encourages code reuse: Abstract classes can define common methods and properties that can be reused by all subclasses. This saves time and reduces code duplication, which can make your code more efficient and easier to maintain.
  • Provides a way to enforce implementation: Abstract methods must be implemented by any concrete subclass of the abstract class. This ensures that certain functionality is implemented consistently across all subclasses, which can prevent errors and improve code quality.
  • Enables late binding: By defining a common interface in an abstract class, you can use late binding to determine which subclass to use at runtime. This allows for greater flexibility and adaptability in your code, as you can change the behavior of your program without changing the code itself.

abstract and final

In java, you will never see a class or method declared with both final and abstract keywords. For classes, final is used to prevent inheritance whereas abstract classes depends upon their child classes for complete implementation. In cases of methods, final is used to prevent overriding whereas abstract methods needs to be overridden in sub-classes.
This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
 


My Personal Notes arrow_drop_up
Last Updated : 06 Mar, 2023
Like Article
Save Article
Similar Reads
Related Tutorials