Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Abstract Method in Java

Last Updated on November 30, 2023 by Ankit Kochar

In the realm of object-oriented programming in Java, the concept of abstract methods plays a crucial role in achieving abstraction and creating flexible class hierarchies. An abstract method is a method declared without implementation in an abstract class or interface, allowing subclasses to provide concrete implementations. Abstract methods enable the creation of abstract classes and interfaces, serving as a blueprint for derived classes to fulfill specific functionalities. This discussion explores the significance of abstract methods in Java, their syntax, and how they contribute to the design and structure of Java applications.

What is Abstract Method in Java?

In Java, an abstract method is a method declared without providing an implementation in the class where it is defined. The purpose of an abstract method is to serve as a placeholder for functionality that must be provided by any concrete (non-abstract) subclass of the class declaring the abstract method. Abstract methods are typically declared in abstract classes or interfaces, and they play a key role in achieving abstraction, encapsulation, and creating flexible class hierarchies.

Syntax of Abstract Method in Java

For defining an Abstract Method in Java, we make use of the “abstract” keyword in Java with the method declaration. The correct syntax for defining an Abstract Method is given as.

abstract returnType methodName(parameterList);

Here, in the above statement

  • abstract: This is the keyword that declares the method as abstract. This also specifies that the method does not contain any implementation.
  • returnType: This specifies the data type of the value that will be returned by the datatype.
  • methodName: It is the name of the method.
  • parameterList: This denotes the list of the parameters that the method accepts.

Rules for Declaring an Abstract Method in Java

Here are the rules for defining abstract methods in Java:

  • Abstract method in Java must be declared using the abstract keyword.
  • Abstract methods must not have a body. They should end with a semicolon instead of a curly brace.
  • Abstract methods must be declared in an abstract class or interface.
  • Abstract methods can only be declared in classes or interfaces that are themselves declared as abstract.
  • All classes that extend an abstract class that has an abstract method must implement the abstract method.
  • Abstract methods can have parameters and a return type, just like any other method.

Examples of Abstract Method in Java

Here are some examples of abstract methods in Java:

Example 1 of Abstract Method in Java
This example shows how to define an abstract method in an abstract class in Java.

Code:

abstract class Animal {
   public abstract void makeSound();
}

class Dog extends Animal {
   public void makeSound() {
      System.out.println("Woof!");
   }
}

class Cat extends Animal {
   public void makeSound() {
      System.out.println("Meow!");
   }
}

public class Main {
   public static void main(String[] args) {
      Animal myDog = new Dog();
      Animal myCat = new Cat();
      myDog.makeSound();
      myCat.makeSound();
   }
}

Output:

Woof!
Meow!

Explanation:
In this example, we have an abstract class Animal that defines an abstract method makeSound(). The subclasses Dog and Cat provide their own implementation of the makeSound() method. When we create objects of the subclasses and call the makeSound() method, it prints out "Woof!" and "Meow!" respectively.

Example 2 of Abstract Method in Java
This example also illustrates the usage of the abstract method in an abstract class in Java.

Code:

abstract class Shape {
   protected double area;

   public abstract void calculateArea();
   public void displayArea() {
      System.out.println("The area is: " + area);
   }
}

class Circle extends Shape {
   private double radius;

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

   public void calculateArea() {
      area = Math.PI * radius * radius;
   }
}

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

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

   public void calculateArea() {
      area = width * height;
   }
}

public class Main {
   public static void main(String[] args) {
      Circle myCircle = new Circle(5);
      Rectangle myRectangle = new Rectangle(10, 20);

      myCircle.calculateArea();
      myCircle.displayArea();

      myRectangle.calculateArea();
      myRectangle.displayArea();
   }
}

Output:

The area is: 78.53981633974483
The area is: 200.0

Explanation:
In this example, we have an abstract class Shape that defines an abstract method calculateArea() and a non-abstract method displayArea(). The subclasses Circle and Rectangle provide their own implementation of the calculateArea() method. When we create objects of the subclasses and call the calculateArea() method, it calculates the area of the shape and sets it to the area variable in the superclass. When we call the displayArea() method, it prints out the area of the shape. In the main method, we have instantiated the objects of both classes and called the functions calculateArea() and displayArea(), and we get the expected output on the screen.

Example 3 of Abstract Method in Java
As mentioned above, In Java, interfaces can also contain abstract methods. An interface is similar to an abstract class in that it provides a set of methods that a class must implement. The difference between Abstract Class and Interface is that an interface can only contain abstract methods which is not in the case of Abstract Classes.

Here’s an example of an interface containing an abstract method in Java:

Code:

interface Drawable {
   public void draw();
}

class Circle implements Drawable {
   private int x, y, radius;

   public Circle(int x, int y, int radius) {
      this.x = x;
      this.y = y;
      this.radius = radius;
   }

   public void draw() {
      System.out.println("Drawing a circle at (" + x + "," + y + ") with radius " + radius);
   }
}

public class Main {
   public static void main(String[] args) {
      Circle myCircle = new Circle(0, 0, 5);
      myCircle.draw();
   }
}

Output:

Drawing a circle at (0,0) with radius 5

Explanation:
In this example, the interface called Drawable has only one abstract method called draw(). Any class that implements this interface must provide an implementation of the draw() method. the Circle class implements the Drawable interface and provides an implementation of the draw() method. The draw() method prints a message to the console indicating that it is drawing a circle at a particular location with a specific radius. In the main method, we instantiated the object of class Circle by passing the arguments as 0, 0, and 5. This results in the printing of the line “Drawing a circle at (0.0) with radius 5” on the output screen.

Advantages of Using Abstract Method in Java

Using abstract methods in Java has several advantages. Some of them are:

  • Abstraction: Using the abstract method in Java helps in achieving abstraction by hiding the implementation details.
  • Flexibility: Abstract methods provide flexibility to the subclasses to provide their own implementation of the method
  • Code Reusability: Abstract methods allow you to reuse the code in the superclass by providing a common interface for a group of subclasses.
  • Encapsulation: Abstract methods help to encapsulate the behavior of an object by defining a common interface for a group of subclasses.
  • Polymorphism: Abstract methods support polymorphism, which allows you to write code that works with objects of different subclasses.

Limitations of Abstract Methods

Using abstract methods in Java also has some limitations. Some of them are:

  • Limited Functionality: Abstract methods only provide a method signature without any implementation. This limits the functionality of the method and makes it less powerful than a regular method.
  • Complexity: Abstract methods can make the code more complex because they require the creation of subclasses to provide an implementation for the method.
  • Inefficiency: Abstract methods can be less efficient than regular methods because they require the use of dynamic binding to call the method at runtime.

Conclusion
In conclusion, abstract methods in Java provide a powerful mechanism for achieving abstraction and creating extensible class hierarchies. By declaring methods without implementations in abstract classes or interfaces, Java encourages the creation of well-defined blueprints that guide the behavior of derived classes. Abstract methods contribute to the design elegance and flexibility of Java programs, allowing developers to build robust and scalable applications through the inheritance and implementation of abstract classes and interfaces.

Frequently Asked Questions (FAQs) related to Abstract Method in Java

Some Frequently Asked Questions related to Abstract Method in Java are given below.

Q1: Can an interface have non-abstract methods in Java?
A1: No, all methods in an interface are abstract by default, and they cannot have a method body. Therefore, an interface can only have abstract methods.

Q2: How is an abstract method declared in Java?
A2:
To declare an abstract method in Java, you use the abstract keyword in the method signature, and it does not include a method body. For example:
abstract class Example {
abstract void abstractMethod();
}

Q3: Can abstract methods be defined in interfaces in Java?
A3:
Yes, interfaces in Java can contain abstract methods. All methods in an interface are implicitly abstract. In Java 8 and later versions, interfaces can also have default and static methods with implementations.

Q4: Why use abstract methods in Java?
A4:
Abstract methods allow the definition of a blueprint in an abstract class or interface, providing a common interface for derived classes. This promotes code reusability, enables polymorphism, and allows for the creation of flexible class hierarchies.

Q5: Can abstract classes have constructors in Java?
A5:
Yes, abstract classes in Java can have constructors. Abstract class constructors are invoked when a concrete subclass is instantiated. Abstract class constructors can also be used to initialize common properties shared by all subclasses.

Leave a Reply

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