Open In App

abstract keyword in java

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

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

Characteristics of Java 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 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 Methods in Java

Sometimes, we require just method declaration in super-classes. This can be achieved 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 a 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 override all the abstract methods of the class.

Important rules for abstract methods

There are certain important rules to be followed with abstract methods as mentioned below:

  • 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 modifiers: 
    1. final
    2. abstract native
    3. abstract synchronized
    4. abstract static
    5. abstract private
    6. abstract strictfp

Abstract Classes in Java

The class which is having partial implementation(i.e. not all methods present in the class have method definitions). 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 a complete implementation. 

For example, java.lang.Number is an abstract class. For more on abstract classes, see abstract classes in Java.

Examples of abstract Keyword

Example 1:

Java




// Java Program to implement
// Abstract Keywords
 
// Parent Class
abstract class gfg {
    abstract void printInfo();
}
 
// Child Class
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);
    }
}
 
// driver Class
class base {
    // main function
    public static void main(String args[])
    {
        // object created
        gfg s = new employee();
        s.printInfo();
    }
}


Output

aakanksha
21
55552.2

Example 2:

Java




// 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 {
    // main function
    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 3:

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 of Abstract Keywords

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 class in Java

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 depend upon their child classes for complete implementation. In cases of methods, final is used to prevent overriding whereas abstract methods need to be overridden in sub-classes.

To know more about the difference between them refer to Difference between Final and Abstract in Java article.



Last Updated : 22 May, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads