Tutorial Playlist
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.
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.
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.
Here is an example:
The above abstract method declaration consists of the following components:
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:
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.
Here are the rules for abstract methods in Java:
Following these rules, you can effectively define and utilize abstract methods in your Java programs.
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.
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.
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.
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.
PAVAN VADAPALLI
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...