Advanced
Data Structures Algorithms & System Design(HLD+LLD)
by Logicmojo

Top tech companies experts provide live online training

Learn Data Structures, Algorithms & System Design

Online live classes from 4 to 7 months programs

Get job assistance after course completion

Download Course Brochure

Back to home
Logicmojo - Updated Jan 22, 2023



One of the main pillars of Java's OOPs ideas is data abstraction. Java programming's abstract classes and interfaces are used to accomplish this. Just so you know, data abstraction is a feature that allows hiding irrelevant information and revealing only the most important and relevant information. For instance, we don't need to be experts in operating protocols and other technical aspects to utilise search engines like Google, Bing, Firefox, and Yahoo.
Let's explore how Java's abstract class might help us achieve data abstraction.
In Java, "abstract methods" refers to methods that are explicitly stated within an abstract class using the abstract keyword. These are referred to be abstract methods in Java since they lack a definition in and of themselves.

What is Abstract class in Java

A class is considered abstract if it contains any abstract methods at all. In addition to some abstract methods, abstract classes can also contain concrete (non-abstract) methods. It is not instantiable. Thus, an object for an abstract class cannot be created for direct access. Additionally, an abstract class may include constructors, static methods, and final methods.
Why would a class be abstract? A Java abstract class offers all of its extended subclasses a single method implementation. It essentially serves as a platform to assist its subclasses without taking centre stage.
Simply placing the word "abstract" in front of a class or method will declare it as abstract.

Syntax:

abstract class Shape 
{
    string color;
    abstract void draw();
}

Through abstraction, the programmer works to make sure that the user only receives the functionality they need in object-oriented programming. To reduce complexity and boost the program's effectiveness, all of its implementation and other auxiliary elements are concealed.

      ⮞ The term "Abstract class" refers to a class that has been declared using the abstract keyword.

      ⮞ A class that is abstract cannot be instantiated, or turned into an object (instance).

      ⮞ Both abstract and non-abstract methods may be included in an abstract class.

      ⮞ If a class has abstract methods, then it must be specified as an abstract class.

      ⮞ One can extend a child class and give each of the parent class's abstract methods an implementation in order to use an abstract class.



Learn More

Why do we need abstract class

No instance of an abstract class can ever be created. Think of this illustration: Assuming we are creating an animal-related software, we might construct various classes like Lion, Dog, Rabbit, etc. As good programmers, we would first create a basic class called Animal that would include traits shared by all animals, such as colour, sound, and so on, as well as behaviours like eating, running, and so forth. Every class will extend this one called Animal and override any required methods.

class Animal{
    public int legs;
    public String name;
    public Animal(){
        
    }
    public String Run(){
        
    }
}
class Lion extends Animal{
    
}
class Cow extends Animal{
    
}

Now, we may create animal classes either directly or by utilising a reference variable of the Animal type. Think about the following instance:

Lion obj = new Lion();
Animal obj = new Lion();

These instantiations are logical. What if we instead instantiate the Animal class?

Animal aniobj = new Animal();

Is it necessary to create an instance of the Animal class? Consider instance variables like legCount and their values. Consider the meaning of a method like sound(). A class that was intended to be extended merely cannot be instantiated.

Abstract Methods

An abstract method is one that has the "abstract" keyword included in its declaration.
A body is absent from an abstract method. The syntax below demonstrates how to end a declaration of an abstract method with a semicolon. A regular (non-abstract) class cannot declare an abstract method; it must always be present inside an abstract class.
Check out that calculator app, for instance. Addition, subtraction, multiplication, and division are the fundamental four operations you need while creating an abstract class called Calculator. Therefore, inside the Calculator class, you just declare them as abstract methods. Therefore, you only need to define the abstract methods whenever you extend the abstract class.

Let's examine a few guidelines for using Abstract Method:

      ⮞ An Abstract method is one that has the abstract keyword declared in its declaration.

      ⮞ Only within an abstract class or interface can an abstract method be declared.

      ⮞ There cannot be any definition or body in an abstract procedure.

      ⮞ The word ";" must be used to terminate the abstract method definition (semicolon).

      ⮞ You must inherit the abstract class in order to create the implementation code for these abstract methods. The definition for the abstract methods can then be written by the child class.

      ⮞ You must declare the child class as abstract if you don't define the abstract method inside of it; otherwise, the compiler will throw an error. Below is an example to help:

abstract class Math_calc {
    abstract void display();
}

class machine extends Math_calc{
    
}
public class Main
{
	public static void main(String[] args) {
		System.out.println("Hello World");
	}
}

Features of Abstract Methods

      ⮞ It is impossible to instantiate.

      ⮞ It may or may not have constructors and abstract methods.

      ⮞ The methods can be final and static, but neither of them can be declared abstract.

      ⮞ A class must be declared abstract if it has any abstract methods.

      ⮞ A different abstract class may extend an abstract class. This suggests that not every abstract method needs to be implemented in the child's abstract class (although it can).

Why Is It So Difficult to Make an Object of an Abstract Class?

You are aware that we cannot instantiate an abstract class if you have read this far. Consequently, it is impossible to create an object of the Abstract class.
Abstract classes are capable of having abstract methods, and an abstract method is one without a body or definition. Thus, it appears that Abstract Class is not a fully developed class. Just a template, really.
As a result, if you construct an object of that abstract class and attempt to access one of the abstract methods, an error will be raised because the method doesn't include any actions.

The abstract method does not contain a body, which is a need for any object to execute a method. Therefore, we are unable to produce any abstract class's objects.
If someone tries to construct an object of an abstract class, they will encounter the following error. student -

Main.java:34: error: learner is abstract; cannot be instantiated
        Learner s = new Learner();
                    ^
1 error

Accessing Constructor

Constructors for abstract classes can be declared. If there isn't a user-defined constructor present, the Java Virtual Machine (JVM) is responsible for creating one for each class in the Java programme. The same holds true for classes that are abstract.

Final Keyword in Abstract class

When you want to designate a variable, method, or class as non-modifiable once-assigned, you use the final keyword. If a variable is final, its value cannot be altered. You cannot inherit a class that has been declared final, and you cannot override a method that has been declared final.
Keep in mind that inheritance is essential to how any abstract class functions. After you extend the abstract class, you can provide its defined abstract methods implementations.
However, if an abstract class is declared final, you cannot inherit it and, as a result, cannot add any logic to the abstract method.

This now goes against every truth about the abstract class. The keywords "final" and "abstract" may be used separately, but not concurrently. Making an abstract entity definitive i s absurd because it is intended to be altered (or overridden).

Key Concepts of Abstract Class

      ⮞ Java's abstract keyword is used to develop abstract classes.

      ⮞ Java prohibits the instantiation of abstract classes.

      ⮞ An abstract method, which lacks a body, can be created using the abstract keyword.

      ⮞ A class must be abstract with the abstract keyword if it has abstract methods; otherwise, the class won't compile.

      ⮞ An abstract class does not necessarily need to contain abstract methods. Even if a class doesn't explicitly declare any abstract methods, we can nonetheless mark it as such.

      ⮞ Java doesn't support multiple class inheritance, so it's best to use an interface if an abstract class doesn't have any method implementations.

      ⮞ Unless the subclass is itself an abstract class, a Java abstract class must implement all abstract methods.

      ⮞ Unless an interface's methods are static or default, all of its methods are implicitly abstract. In Java 8, static methods and default methods were added to interfaces. For additional information, see Java 8 interface modifications.

      ⮞ Without even giving the implementation of interface methods, Java Abstract classes can implement interfaces.

      ⮞ The Java Abstract class is used to offer default implementation or to provide a uniform method implementation to all subclasses.

      ⮞ If an abstract class contains a main() method, it can be run in Java just like any other class.

Characteristics of Abstract Class

Template
By giving programmers the opportunity to conceal the code implementation, the abstract class in Java offers the best way to carry out the process of data abstraction. It also provides a template that outlines the procedures to the user.

Unstable Coupling
Java's data abstraction facilitates loose coupling by exponentially reducing dependencies.

Reusability of Code
It saves time to use an abstract class in the code. Anywhere that the abstract method is required, we can call it. Abstract classes eliminate the need to repeatedly write the same code.

Abstraction
By condensing the project's complete features to just those that are required, data abstraction in Java enables developers to conceal the code complexity from the end user.

Dynamic Resolution Method
Dynamic Method Resolution is the final but not the least step. The dynamic method dispatch or method resolution processes are made possible by the abstract classes. An overridden method's call is resolved through a process called dynamic method resolution.
RunTime polymorphism is implemented in this way. Every time a method that has been overridden is called by reference, the JVM is in charge of determining which version of the method to use depending on the type of object.

Implementation of Interface using Abstract Class

Interface, which is denoted by the keyword interface, only contains abstract methods that cannot be implemented. In Java, an abstract class is one that uses the abstract keyword in its declaration. It is conceivable for this class to have no methods at all, though often there is at least one abstract method that cannot be implemented. An abstract class instance cannot be created.
Since an interface's methods are all abstract, we can implement it with an Abstract Class at this point.

interface Logicmojo {
    void learnCoding();
    void learnProgrammingLanguage();
    void getjob();
}

Let's now put the interface into action in a Student-named Abstract class.

abstract class candidate implements Logicmojo {
    
    
    @Override public void learnCoding()
    {
        System.out.println(
            "Let's make coding a habit with Logicmojo");
    }
    @Override public void learnProgrammingLanguage()
    {
        System.out.println("Let's master all fundamentals of java with the help of Logicmojo");
    }
}

Why can't static methods in Java be abstract?

A static method in Java cannot be abstract. Compilation errors will result from doing this.
What will happen if an abstract static method is created?
assuming we abstract a static method. The procedure will then be expressed as:
Situation 1: When a method is designated as abstract using the abstract type modifier, it is the subclass's job to implement it because the superclass has not indicated how to do so. Therefore, in order to give method definition, a subclass must override them.

Situation 2: Since static members are compile-time components and overriding them turns them into runtime elements, it is now evident when a method is specified as static that it cannot be overridden by any subclass (it is hidden) (Runtime Polymorphism).

The func method must have a definition in the subclass if it is described as abstract in Scenario 1. The static func method, however, cannot be overridden in any subclass, hence Scenario 2 states that it cannot have a definition. Thus, the situations appear to be at odds with one another. Thus, our presumption that a static func method is abstract is incorrect. Consequently, a static method is unable to be abstract.
The approach will then be codified as:

import java.io.*;
abstract class A {

	static void func()
	{
		System.out.println(
			"Static method implemented.");
	}

	abstract void func1();
}

class B extends A {
	void func1()
	{
		System.out.println(
			"Abstract method implemented.");
	}
}

public class Demo {
	public static void main(String args[])
	{

		B.func();
		B b = new B();
		b.func1();
	}
}

Difference Between Abstract Class and Concrete Class

Abstract ClassConcrete Class
for a group of classes, represents a generalised type.represents an object type for its types.
constructs API agreements for an abstractiondefines the items' structure and behaviour
No instantiationable to instantiate
Both abstract and non-abstract methods are included.only includes abstract techniques
Abstraction-based techniques lack a body or implementation.A concrete class must implement each of its superclass's abstract methods.
A class or function that is abstract cannot be "final."Any concrete method or class may become "final."


Difference Between Abstract Class and Interface

Abstract ClassInterface
No full abstraction is provided by an Abstract class.The interface does offer complete abstraction.
We are unable to establish multiple inheritance using Abstract classes.We can achieve multiple inheritance via an interface.
Access modifiers can be specified for a member of an abstract class.Because everything in an interface is public by default, we are unable to utilise any access modifiers there.
Only one abstract class may be inherited by a class.Several interfaces may be implemented by a class (Multiple Inheritance).
Both abstract and non-abstract methods can be found in an abstract class.There can only be abstract methods in an interface.


Conclusions

This concludes our discussion of "Abstract Class in Java." I sincerely hope that you learned something from it and that it improved your knowledge. You can consult the Java Tutorial if you want to learn more about Java.

Good luck and happy learning!