Home Java Abstract Class in Java

Abstract Class in Java

In Java, an abstract class is a superclass that cannot be instantiated and is used to declare or specify general properties. A Java abstract class is not applicable in creating an object; attempting to do so will result in a compiler error. The keyword abstract is used to declare the abstract class.

Subclasses extended from an abstract class inherit all of the abstract class’s attributes and subclass-specific attributes. The abstract class declares the class’s traits and implementation methods, thus defining the entire interface.

Subclasses of abstract classes use them as templates. The abstract class Tree and its subclass Test_Tree, for example, have all of the features of a tree as well as others that are unique to the Test_Tree.

It’s crucial to know the distinction between an abstract class and an interface. An abstract class may have abstract methods, member variables, and concrete methods, whereas an interface only has method declarations or abstract methods and constant data members. A class can implement many interfaces but only extend one abstract class because Java only supports single inheritance.

Abstract Class in Java

An abstract class aims to serve as a base for subclasses. However, a Java abstract class can’t be instantiated, which means you can’t create new instances of it. This Java abstract class tutorial will show you how to construct abstract classes in Java and what rules apply. At the end of this text, this tutorial delves deeper into the purpose of abstract classes in Java.

Declare an abstract class

In Java, the abstract keyword is added to the class definition to indicate that the class is abstract. Here’s an example of a Java abstract class:

public abstract class AbstractClassDefinition {
  
  }

Declaring an abstract class in Java is as simple as that. You can no longer create AbstractClassDefinition instances. As a result, the Java code below is not valid:

AbstractClassDefinition classInstance = new AbstractClassDefinition();

Any attempts to compile the code above will generate an error message claiming that AbstractClassDefinition is an abstract class, and you can’t instantiate it.

Abstract type of Methods

Abstract methods are found in abstract classes. You can make a method abstract by placing the abstract keyword in front of the method definition. Here’s an example of a Java abstract method:

public abstract class AbstractClassDefinition {
  
public abstract void newAbstractMethod();

}

There is no implementation for an abstract method. It contains a method signature in the same way that methods in a Java interface work.

On the off chance that a class has an abstract method, it must be declared abstract as a whole. An abstract class does not have to have all of its methods as abstract methods. There can be a mix of abstract and non-abstract methods in an abstract class.

All abstract methods of an abstract superclass must be implemented (overridden) by subclasses. The superclass’s non-abstract methods are inherited in their current state. If necessary, they are overridden. An example subclass of the abstract class AbstractClassDefinition is as follows:

public class AbstractSubClass extends AbstractClassDefinition {
  
public void abstractMethod() {
    System.out.println("implementation of abstract method ");
}

}

Notice how AbstractSubClass must implement the abstract method abstractMethod() from AbstractClassDefinition, which is an abstract superclass. Only when a subclass of an abstract class is also an abstract class is it not required to implement all of its superclass’s abstract methods.

Abstract Classes: What Are They Good For?

Abstract classes are intended to serve as basic classes that subclasses can enhance to provide a complete implementation. Consider the following scenario: A given process necessitates three steps:

  • The first step before taking action.
  • The action taking place.
  • The action’s follow-up step.

When steps prior to and after the ‘action’ are always the same, this Java code is used to implement the 3-step process in an abstract superclass:

public abstract class AbstractProcessDefinition {
  
public void process() {
    actionStepBefore();
    realAction();
    actionStepAfter();
}

public void actionStepBefore() {
    //implementation directly in abstract superclass
}

public abstract void realAction(); // implemented by subclasses

public void actionStepAfter() {
    //implementation directly in abstract superclass
}

}

Take note of how abstract the realAction() method is. AbstractProcessDefinition subclasses can now extend AbstractProcessDefinition by simply overriding the realAction() function. When the subclass’s process() function is invoked, the entire process is run, including the abstract superclass’s actionStepBefore() and actionStepAfter() methods, as well as the subclass’s realAction() method.

AbstractProcessDefinition does not necessarily have to be an abstract class to work as a base class. The realAction() method didn’t need to be abstract either. You might have just used a regular class instead. By making the method to implement abstract, and thus the class, you are signaling to users of this class not to utilize it in its current state. Instead, it should be used as a foundation class for subclasses, with the abstract function implemented in the subclass.

The realAction() method in the preceding example has no default implementation. In some circumstances, your superclass’s method that subclasses are expected to override may have a default implementation. You can’t make the method abstract in such an instance. Even if the superclass doesn’t have abstract methods, you can still make it abstract.

Here’s a more detailed example that opens a URL, processes it, and closes the URL connection.

public abstract class URLProcessorDefinition {

public void processINFO(URL url) throws IOException {
    URLConnection urlConn = url.openConnection();
    InputStream inStream = urlConn.getInputStream();

    try{
        URLDataProcessing(input);
    } finally {
        inStream.close();
    }
}

protected abstract void URLDataProcessing(InputStream inStream)
    throws IOException;
  
}

URLDataProcessing() is an abstract method, and URLProcessorDefinition is an abstract class, as you can see. Because URLDataProcessing() is an abstract function, subclasses of URLProcessorDefinition must implement it.

Subclasses of the URLProcessorDefinition abstract class can process data obtained from URLs without worrying about the URL’s network connection being opened and closed. The URLProcessorDefinition is in charge of this. Only the data from the InputStream given to the URLDataProcessing() function needs to be processed by subclasses. It simplifies the creation of classes that process data from URLs. The following is an example of a subclass:

public class URLProcessorImplementation extends URLProcessorDefinition {

@Override
protected void URLDataProcessing(InputStream inStream) throws IOException {
    int int_data = inStream.read();
    while(int_data != -1){
        System.out.println((char) int_data);
        int_data = inStream.read();
    }
}

}

It’s worth noting that the subclass implements the URLDataProcessing() method. On the flip side, the URLProcessorDefinition superclass is responsible for the rest of the code. An example of how to utilize the URLProcessorImplementation class is as follows:

URLProcessorImplementation urlProcessor = new URLProcessorImplementation();
urlProcessor.process(new URL("https://www.codeunderscored.com/"));

The URLProcessorDefinition superclass implements the processINFO() function, which is called. This function then invokes the URLProcessorImpl class’s URLDataProcessing() method.

The Template Method Design Pattern with Abstract Classes

The URLProcessorDefinition class demonstrates the Template Method design pattern in the preceding example. When subclasses extend the Template Method base class, the Template Method design pattern partially implements a process that subclasses can complete.

Conclusion

An abstract class is a class that is declared with the “abstract” keyword. It can have abstract and concrete methods without a body and standard methods with the body. Abstract methods aren’t allowed in non-abstract classes. Unless another class extends it, an abstract class is useless. In this tutorial, you’ve discovered what an abstract class is, why we use it, and what guidelines we should follow when working with it in Java.

The declaration of an abstract method necessitates the declaration of a class as abstract. It’s not always true in the other direction: a class can be designated as abstract even if it has no abstract methods. It can also have a non-abstract (concrete) method. In addition, you can’t have abstract methods in a concrete class.

You may also like

Leave a Comment