top

Search

Java Tutorial

.

UpGrad

Java Tutorial

Abstract Method in Java

Overview

This tutorial will introduce learners to some of the most essential concepts of an abstract method in Java. It addresses what an abstract method is, followed by concepts regarding the rules of the abstract method in Java and examples of abstract methods in Java, among others. 

What is an Abstract Method in Java?

In Java, an abstract method is a method declaration lacking implementation. It is declared using the "abstract" keyword and contains no code block. 

Abstract methods are meant to be overridden by subclasses or implemented by classes that implement an interface. They serve as placeholders, defining a method's signature and specifying that any concrete class inheriting from an abstract class or implementing an interface must implement that method.

Abstract methods allow for polymorphism and provide a way to define a common interface that can be shared across different classes while allowing each class to provide its own implementation. Using abstract methods, you can enforce a consistent behavior across multiple classes and enable runtime polymorphism through method overriding.

Syntax of the Abstract Method in Java

An abstract method can only be declared within an abstract class or interface. Classes containing abstract methods must also be declared abstract using the abstract keyword. Subclasses inheriting from an abstract class or implementing an interface with abstract methods are required to provide an implementation for all the abstract methods declared.

Here is the syntax of an abstract method in Java:

[access modifier] abstract [return type] methodName([parameters]);

Now, let us break down each placeholder of the syntax to understand it better.

  • Access modifier: It specifies the visibility or accessibility of the abstract method. It can be one of the following: public, protected, private, or no modifier (default visibility within the package).

  • abstract: It is a keyword that indicates the method is abstract and does not have an implementation.

  • Return type: It represents the data type of the value the method returns. Use void if the method does not return any value.

  • Method name: It is the name of the abstract method.

  • Parameters: They specify the data type and names of the input parameters (if any) that the abstract method accepts. Parameters are optional.

Here is an example:

The above abstract method declaration consists of the following components:

  • public as the access modifier.

  • abstract as the keyword indicating it's an abstract method.

  • void as the return type indicating no return value.

  • methodName as the name of the method.

  • (int parameter1, String parameter2) specifying the two parameters, an int named parameter1 and a String named parameter2.

The purpose of an abstract method is to provide a declaration without an implementation. Thus, the abstract class or interface containing this method expects its subclasses or implementers to provide the implementation details. Subclasses inheriting from the abstract class or implementing the interface must override this abstract method and provide the necessary implementation.

For example, if we have an abstract class ExampleClass with the abstract method exampleMethod such as this:

Then, in this case, we would need a subclass of ExampleClass to provide an implementation for the exampleMethod method like this:

Why Create an Abstract Method in Java?

The abstract method in Java defines a common interface or contract that must be fulfilled by subclasses or implementing classes. They allow you to specify the required methods that must be implemented by the derived classes while leaving the specific implementation details to those classes.

Abstract methods promote code reusability and enable polymorphism. By defining abstract methods in an abstract class or interface, you can create a blueprint or template for a group of related classes. This allows you to define common behavior or functionality that can be shared among those classes. It also provides a way to ensure that all subclasses or implementing classes adhere to a certain set of rules or behaviors.

Another benefit of abstract methods is that they allow you to achieve runtime polymorphism. Abstract methods are overridden by subclasses or implementing classes. Hence, you can create instances of those classes and invoke the abstract methods. These will execute the specific implementation provided by each class. This allows for flexibility and extensibility in the design of your Java programs.

Overall, abstract methods are crucial in creating modular, reusable, and flexible code structures in Java. They provide a powerful mechanism for defining standard interfaces, enforcing behavior, and enabling polymorphism.

Rules of Abstract Method

Here are the rules for abstract methods in Java:

  • Abstract methods must be declared in an abstract class or an interface.

  • Abstract methods are defined using the "abstract" keyword, followed by the method signature and a semicolon. They do not provide an implementation.

  • Any class that extends an abstract class or implements an interface containing an abstract method must provide an implementation for that method.

  • Abstract methods cannot be declared in a regular class. Instead, they are allowed in abstract classes or interfaces.

  • Abstract methods cannot be marked as final or private. This is because they are meant to be overridden or implemented by subclasses.

  • A class can inherit from an abstract class that contains abstract methods. If this happens, it must either be declared abstract or implement all the abstract methods.

  • Abstract methods can have parameters and a return type. This is just like regular methods.

  • Abstract methods can be overridden in subclasses. This is done by using the "override" keyword to provide a concrete implementation.

Following these rules, you can effectively define and utilize abstract methods in your Java programs.

An Abstract Method in Java Interface

Abstract methods can also be declared within interfaces in Java. When an abstract method is declared within an interface, any class implementing that interface must provide an implementation for that method.

Here's an example of declaring an abstract method in a Java interface:

When a class implements an interface containing an abstract method, it must provide an implementation. For example:

In the example above, the ExampleClass implements the ExampleInterface interface and provides an implementation for the exampleMethod defined in the interface.

Interfaces in Java can contain multiple abstract methods, allowing you to define a contract that implementing classes must fulfill. By using interfaces and abstract methods, you can achieve abstraction, and polymorphism, and ensure consistency across different classes that implement the same interface.

Here is a working example of an abstract method in a Java interface.

Code for main.java file:

// Main class to test the implementation
public class Main {
    public static void main(String[] args) {
        // Create an instance of MyClass
        MyClass myObj = new MyClass();

        // Call the abstract method
        myObj.abstractMethod(); // Output: "Implementation of abstractMethod in MyClass"

        // Call additional method in MyClass
        myObj.otherMethod(); // Output: "OtherMethod implementation in MyClass"
    }
}

In the Main class, we create an instance of MyClass, call the abstractMethod(), and an additional method otherMethod() defined in MyClass. When we run the Main class, it will output the messages specified in the implementation.

Code for MyInterface.java file:

// Define an interface with an abstract method
public interface MyInterface {
    void abstractMethod();
}

Here we define the MyInterface interface, which contains the abstract method abstractMethod().

Code for MyClass.java file:

// Implement the interface in a class
public class MyClass implements MyInterface {
    public void abstractMethod() {
        System.out.println("Implementation of abstractMethod in MyClass");
    }


    // Additional methods and implementation in MyClass
    public void otherMethod() {
        System.out.println("OtherMethod implementation in MyClass");
    }
}

Finally, we create a class MyClass that implements the MyInterface. This class implements the abstractMethod() by printing a specific message.

An Abstract Method in Java Example

Here's an example of an abstract method in Java:

abstract class Shape {
    public abstract double area();
}

class Circle extends Shape {
    private double radius;

    public Circle(double radius) {
        this.radius = radius;
    }

    public double area() {
        return Math.PI * radius * radius;
    }
}

class Rectangle extends Shape {
    private double length;
    private double width;

    public Rectangle(double length, double width) {
        this.length = length;
        this.width = width;
    }

    public double area() {
        return length * width;
    }
}

public class Main {
    public static void main(String[] args) {
        Circle circle = new Circle(5.0);
        Rectangle rectangle = new Rectangle(4.0, 6.0);

        System.out.println("Area of circle: " + circle.area());
        System.out.println("Area of rectangle: " + rectangle.area());
    }
}

In this example, the Shape class is an abstract class that defines an abstract method area(). This method is not implemented in the Shape class itself, but it is declared using the abstract keyword. The Circle and Rectangle classes implement the area() method and extend the Shape class.

The area() method calculates and returns the area of the respective shape. Since the area() method is declared as abstract in the Shape class, any concrete subclass of Shape must implement this method. In this example, the Circle and Rectangle classes override the area() method to provide their own specific implementations.

In the main method, we create instances of Circle and Rectangle and call the area() method on them to calculate and display their respective areas.

Conclusion

The abstract method in Java plays an integral role in object-oriented programming. It provides a mechanism for defining common behavior. It also allows specific implementation details to be handled by subclasses or implementing classes.

Although sufficient study material is available online for Java, guidance from experts can help you learn better. If you are an aspiring programmer or software developer, you should consider taking up online degree courses by upGrad. Industry experts teach these courses and will help you gain a sound understanding of the various concepts of Java.

FAQs

1. Can we have a non-abstract method in an abstract class?

An abstract class can contain abstract and non-abstract (concrete) methods. Non-abstract methods in an abstract class can have a complete implementation.

2. Can an abstract class have a constructor?

Yes, an abstract class can have a constructor. However, the constructor of an abstract class is invoked when a subclass object is created. It cannot be directly instantiated.

3. Can an abstract method be final or static?

No, abstract methods cannot be marked as final or static. Abstract methods are meant to be overridden by subclasses, and the final and static keywords restrict method overriding.

Leave a Reply

Your email address will not be published. Required fields are marked *