Abstract Class in Java – Learn with its Important Rules and Example

Abstract Classes are something you would normally call a blueprint of an actual class. A real-life example would be a model of an airport. When engineers need to build an airport in a given piece of land, they would first create a blueprint and then create a miniature model of the airport.

In the model, they would put little airplanes in the hangars to signify the position of the hangars. An abstract class functions in the same way. The abstract class is the miniature model and the abstract methods are miniature airplanes. It just signifies the pattern but does not implement them. Let us learn more about Abstract Class in java.

Abstract class in java

Keeping you updated with latest technology trends, Join DataFlair on Telegram

Abstract Methods in Java

Before you start to learn about abstract classes, you should know what abstract methods are. Methods that do not possess a concrete definition or a body are abstract methods in Java. Abstract methods do not have a concrete definition. They just contain the method signature.

An abstract method must always be inside an abstract class. However, an abstract class does not necessarily need to have an abstract method. If you want to inherit an abstract class you must provide a definition for all of the abstract methods in the parent class. If you cannot provide a definition for all the abstract methods in the parent class, then you have to declare the child class abstract as well.

Need for Java Abstract Class

Whenever you need to implement a method differently in different classes we use an abstract class. We can also use abstract classes to make it compulsory for child classes to implement a single method.

For example, if I have a class called “Bank” which has a method namely “CalcInterest”, I can keep this method as abstract. All the banks have a different way of calculating the interest. So each class would derive this method and implement it in their own way. However, it is compulsory for all the child classes to provide a concrete definition of the CalcInterest method. This is why abstract classes are useful.

Ways to achieve Abstraction in Java

Ways to achieve Abstraction in Java

  1. Abstract class
  2. Interfaces

1. Abstract Classes in Java

Abstract classes in Java are pretty simple to understand. Any class which contains at least a single abstract method in itself is an abstract class.

Declaring Abstract Classes in Java

Syntax of Java Abstract Class:

abstract class <class-name>

abstract class <class-name>
{
 //class definition
}

and that of an abstract method is

abstract <return-type><method-name>(<parameters>);

If we try to create an object of the abstract class it will throw an error: class is abstract. cannot be instantiated.

Key points for Java abstract class:

  1. You always have to declare an abstract class with an abstract keyword.
  2. Remember that you do not need to have all the methods in the abstract class as abstract. You can also have concrete methods inside an abstract class.
  3. Once you declare the abstract methods you have to redefine these methods in the subclass. This goes on to say that method overriding is compulsory if you inherit an abstract class.
  4. However, you can ignore the definition if the class you are inheriting and the child class are abstract classes. This means you do not have to override the methods in the parent class if your current class is also abstract like the parent class.
  5. Note that the class has to be abstract if any one of its methods is abstract.
  6. An abstract class cannot have instances of itself. In layman’s terms, you cannot have an object of a class that is abstract. But you can have objects which reference to an abstract class.
  7. The compiler calls the constructor of the abstract class when the program creates an object of the child class.
  8. If you want to create classes that one can only inherit and not create, we can have only concrete methods inside an abstract class.
  9. You can also include final methods in an abstract class.
  10. A final class cannot have abstract methods.
  11. It is also not possible for a single class to extend multiple abstract classes in Java. If you want to implement multiple inheritances you have to use interfaces.

Why can’t we create an object of an abstract class in Java?

Simply knowing the rules is not enough. In order to truly learn a concept, you should question as to why something is not allowed rather than simply acknowledging it.

So why can’t we create an object of an abstract class? Well, the answer is simple. The abstract class does not contain concrete methods. Let us say that abstract classes could have instances of themselves. If a programmer tried to access the methods of the abstract class by using the object what would the compiler do? It would run into errors because it would not be able to execute an abstract method! To avoid this problem, java prohibits the creation of instances of abstract classes.

Inheriting Java Abstract Class

You can never create instances of an abstract class. So how do you use it then? Yes, you use inheritance. Generally, child classes which are primarily concrete, inherit these abstract classes and provide definition to them.

Java example to illustrate the inheriting of an abstract class:

package com.dataflair.abstractclass;
abstract class AbstractClass {
  public abstract void method1();

}
public class InheritAbstract extends AbstractClass {
  //This class inherits the AbstractClass and redefines the abstract method
  public void method1() {
    System.out.println("This was an abstract method but now it has a definition");
  }
  public static void main(String[] args) {
    InheritAbstract ob = new InheritAbstract();
    ob.method1();
  }
}

Output

This was an abstract method but now it has a definition

Now let us look at an example that would absolutely clear all of our concepts.

Java program to illustrate the use of abstract classes in Java:

package com.dataflair.abstractclass;
import java.io.IOException;

abstract class AbstractClass {
  AbstractClass() {
    //This is the constructor
    //This gets called when during object creation of child class. 
    System.out.println("This is the constructor of the parent abstract class. ");
  }

  final void finalmethod() {
    System.out.println("This method is a final method. You cannot override this method. ");
  }
  public abstract void abstractmethod();
}

public class AbstractClassExample extends AbstractClass {
  public void abstractmethod() {
    System.out.print("This is an example of an abstract method redefined inside child class. ");
  }
  public static void main(String[] args) throws IOException {
    AbstractClass object = new AbstractClassExample();
    //We can not define an object of abstract class but we can refer to it.
    object.finalmethod(); //final method in java
    object.abstractmethod(); //calling the abstract method
  }
}

Output

This is the constructor of the parent abstract class.
This method is final. You cannot override this method.
This is an example of an abstract method redefined inside child class.

Accessing Constructors of Abstract Class

In Java, whenever you create an object of the child class, the parent class constructor automatically gets called. This is done by the JVM. However, if you want to explicitly call the parent class constructor, then the super keyword is helpful. The super() command calls the parent class constructor. However, the super() call must be the first line of definition inside your child class constructor. Let us look at an example.

Java program to illustrate the process of accessing constructors of parent class:

package com.dataflair.abstractclass;
abstract class AbstractClass {
  AbstractClass() {
    System.out.println("This is the Abstract Class constructor. ");
  }
  public abstract void method1();

}
public class InheritAbstract extends AbstractClass {
  InheritAbstract() {
    super();
    System.out.println("This is the child class constrcutor");
  }
  //This class inherits the AbstractClass and redefines the abstract method
  public void method1() {
    System.out.println("This was an abstract method but now it has a definition");
  }
  public static void main(String[] args) {
    InheritAbstract ob = new InheritAbstract();
    ob.method1();
  }
}

Output

This is the Abstract Class constructor.
This is the child class constructor
This was an abstract method but now it has a definition

You can try and remove the super keyword and you will observe that the output remains the same.

Real-life Scenarios where Abstract Classes are Useful

Up until now, we learned about abstract classes and the rules for them. Let us now look at a real-life scenario where we use abstract classes.

Program to illustrate real-life usage of abstract classes in Java:

package com.dataflair.abstractclass;
abstract class LoginCreateAbstract {
  abstract public void createLogin();
  //This is the basic blueprint of the function for the backend of a website
}
class LoginCreateUser1 extends LoginCreateAbstract {
  public void createLogin() //the function gets implemented in this Class. 
  {
    System.out.println("This is the login for User-1 ");
  }
}
class LoginCreateUser2 extends LoginCreateAbstract {
  public void createLogin() {
    System.out.println("This is the login for User-2");
  }
}
public class RealLifeExample {
  public static void main(String[] args) {
    LoginCreateAbstract login1 = new LoginCreateUser1();
    LoginCreateAbstract login2 = new LoginCreateUser2();
    login1.createLogin();
    login2.createLogin();
  }
}

Output

This is the login for User-1
This is the login for User-2

This is a simulation of how different logins will be created for different users. This is a real-life use of an abstract class that lays out a blueprint of all the methods. The classes respectively provide a different definition of the same method. This eliminates the need for new method names for the same function. This also reduces code redundancy and makes it easy to debug.

Difference between Java Concrete Class and Abstract Class

Abstract classes are indeed, very different from concrete classes. How? Let us see.

  1. Concrete classes cannot have abstract methods but abstract classes can have abstract methods.
  2. Abstract classes cannot exist by themselves. They need a concrete class to inherit it and provide definition to its abstract methods. On the other hand, a concrete class can exist independently.
  3. A concrete class can not have abstract methods but an abstract class may have only concrete methods.

Summary

In this article, we learned about abstract class in java, how to use them, and how they are useful for programmers while developing complex projects. Hope you liked the article.

Do share your DataFlair Review to let us know your experience with us.

Leave a Reply

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

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.