Browse Tutorials
Abstract Class in Java: Concepts, Examples, and Usage

Abstract Class in Java: Concepts, Examples, and Usage

18 Apr 2024
Intermediate
2.3K Views
19 min read
Learn via Video Course & by Doing Hands-on Labs

Java Programming For Beginners Free Course

Abstract Class in Java: An Overview

Abstract Class in Java is an implementation of Abstraction in Java. It hides the logic and showcases the desired result. In this Java tutorial, we'll take a look at how Java abstraction works, what its advantages are, examples, abstract methods in Java example, and some tips for getting started with implementing abstractions into your codebase.

Read More - Top 50 Java Interview Questions For Freshers

Abstract Class in Java

  • Abstraction in Java is a powerful concept that enables developers to create complex applications without having to worry about low-level details such as data type and variables in Java, memory management, and platform independence.
  • It’s achieved by simplifying complex code, hiding details of how things work, and providing developers with the ability to handle detailed operations without losing track of the bigger picture.
  • Through the use of concepts like abstract classes, methods, interfaces, superclasses, and polymorphism, abstraction in Java streamlines development by hiding complicated features.
  • It enables developers to concentrate on the crucial elements, making code upkeep and feature additions simpler.

Example of Abstraction Program in Java


abstract class Animal {
    private String name;

    public Animal(String name) {
        this.name = name;
    }

    // Abstract method to be implemented by subclasses
    public abstract void makeSound();
}

 class Dog extends Animal {
    public Dog(String name) {
        super(name);
    }

    // Implementation of the abstract method
    public void makeSound() {
        System.out.println("Woof!");
    }
}

public class Main {
    public static void main(String[] args) {
        // Create an instance of Dog using the Animal reference
        Animal myDog = new Dog("Fido");
        // Call the makeSound() method of Dog
        myDog.makeSound();
    }
}

The abstract class "Animal" in this Java code has the method "makeSound," whereas the concrete subclass "Dog" overrides "makeSound" to print "Woof!" when a "Dog" object is created and called in the "main" method.

Output

Woof!

Ways to achieve Abstraction Class in Java

  • Programming in Java requires abstraction.
  • To construct universal methods shared by related objects, abstract classes—which cannot be instantiated—are used.
  • Different classes of behavior protocols are defined via interfaces.
  • By separating classes from one another, inner classes provide abstraction.
  • From other code segments, packages conceal the specifics of items.
  • Java programming can achieve effective abstraction by using these methods.

Read More - Java Developer Salary In India

When to use Abstract classes and abstract method

  • Superclasses don't have to implement every method to define the structure of an abstraction.
  • Superclasses can offer a generalization that all subclasses share, enabling each subclass to offer particular specifics.
  • Shapes are used as an example, where the base type "shape" is defined with typical characteristics like color and size.
  • Particular forms like circles, squares, and triangles derive from the basic class "shape".
  • Subclasses might include extra traits and actions like flipping for specific shapes.
  • Subclasses can manage behavioral variations like calculating area.
  • The type hierarchy identifies the differences and similarities among shapes.

Abstract Class in Java

  • An abstract class in Java serves as a blueprint for other classes so that they can share abstractions and implementations.
  • It is the superclass that contains mixtures of abstract methods, which have to be overridden by subclasses, and concrete methods, which can be used without modification.
  • By creating abstract classes and abstract methods, Java allows developers to enforce a design pattern that must be implemented at the subclass level.
  • Abstract classes provide a foundation for better code structure by providing abstract methods to act as building blocks for more specific functionality.
  • Ultimately, abstract classes can help developers develop well-structured programs and reduce repetitive coding.

Example


abstract class Shape {
    int numSides;

    public Shape(int numSides) {
        this.numSides = numSides;
    }

    public abstract double getArea();
}

class Rectangle extends Shape {
    int length, width;

    public Rectangle(int length, int width) {
        super(4);
        this.length = length;
        this.width = width;
    }

    public double getArea() {
        return length * width;
    }
}

public class Main {
    public static void main(String[] args) {
        Shape rect = new Rectangle(5, 10);
        System.out.println("Number of sides: " + rect.numSides);
        System.out.println("Area of rectangle: " + rect.getArea());
    }
}

This example in the Java Compiler creates an abstract class called "Shape" with the fields "numSides" and "getArea()." A "Rectangle" class is then added to it, which determines a rectangle's area. A rectangle object is created in the "Main" class, and its area and number of sides are printed.

Output

Number of sides: 4
Area of rectangle: 50.0

Abstract Method in Java

  • Abstract methods in Java are a type of method declaration that lacks an implementation.
  • They are a fundamental concept in Object-Oriented Programming.
  • Abstract methods cannot be implemented within their class, and other classes must extend the parent abstract class and provide their own implementation for the abstract method.
  • Abstract methods serve a useful purpose when the desired behavior of the method should remain consistent while allowing different implementations within different classes.
  • They are commonly used when dealing with polymorphism and inheritance, helping to reduce code duplication and simplify code structure.
  • Abstract methods help keep code easier to maintain by designating differences between different objects whilst keeping related behaviors similar.

Example


class Shape {
    // Placeholder class for the sake of demonstration
    // It could have methods and fields related to shapes in general
}

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

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

    public double getArea() {
        return length * width;
    }
}

public class Main {
    public static void main(String[] args) {
        // Create a rectangle object with length 5 and width 3
        Rectangle rectangle = new Rectangle(5, 3);

        // Calculate and print the area of the rectangle
        double area = rectangle.getArea();
        System.out.println("Area of the rectangle: " + area);
    }
}

The "Rectangle" class in this example is an inheritor of the "Shape" class. When the "getArea()" method is used, it computes and returns the area of a rectangle depending on its length and width.

Output

Area of the rectangle: 15.0

Interface in Java

  • Interface in Java can be an incredibly useful tool for creating robust and extensible software.
  • A Java Interface allows developers to define a set of related methods that must be implemented by classes that implement the Interface, providing access to the same types of data regardless of the concrete implementation.
  • This helps enforce coding standards and conventions while allowing developers maximum flexibility in implementing parts of a program.
  • Interfaces are also used to increase modularity, improving scalability, reuse, and significant reductions in development time.
  • Interface usage is ubiquitous within server-side application development with frameworks such as Spring providing an Interface-based approach to developing applications.

Example of interface program in Java


// Define the interface
interface Animal {
  public void makeSound();
}
// Define a class that implements the interface
class Cat implements Animal {
  public void makeSound() {
    System.out.println("Meow");
  }
}
// Define another class that implements the interface
class Dog implements Animal {
  public void makeSound() {
    System.out.println("Woof");
  }
}
// Test the interface and the classes that implement it
public class InterfaceExample {
  public static void main(String[] args) {
    Animal myCat = new Cat();
    Animal myDog = new Dog();
    myCat.makeSound();
    myDog.makeSound();
  }
}

This example in the Java Online Editor shows how to use the "Animal" interface and its two implementing classes, "Cat" and "Dog." It enables the "makeSound()" method, which prints out the corresponding noises "Meow" and "Woof" when called in the "main" method, to be called by objects of these types.

Output

Meow
Woof

Advantages of Abstraction in Java

  • It reduces the complexity of viewing things.
  • Hides implementation details and exposes only relevant information.
  • Supports modularity, as complex systems can be divided into smaller and more manageable parts.
  • Improves code reusability and maintainability.
  • Increases security by preventing access to internal class details.

A real-life Example of Data Abstraction in Java

  • Real-world data abstraction is comparable to a dashboard for an automobile.
  • It makes complex internal systems simpler while giving drivers access to crucial information like speed and fuel level.
  • This abstraction protects drivers from minute details so they can concentrate on driving.
  • It conceals the implementation, allowing the driver to see changes and the flexibility of the car.

Encapsulation vs Data Abstraction

EncapsulationData Abstraction
They are combining methods and data into one class, and limiting access to data members.By creating classes based on crucial traits and behaviors, complicated systems can be made simpler.
Control over who has access to private data.Exposing key functionalities while obscuring implementation details.
Access modifiers (such as private, protected, and public) are used to do this.Emphasizes the development of abstract methods and high-level interfaces.
Giving regulated access helps maintain the security and integrity of data.Reducing complexity, making it easier to maintain, and offering a clear interface.
Using public getter/setter methods and private fields to access and change data.Developing abstract classes or interfaces that have abstract methods that subclasses can implement.

Why do we use an Interface in Java?

Here are some reasons why we use interface in Java:

  • To achieve abstraction: Interfaces can be used to achieve abstraction, which is an important aspect of object-oriented programming. By defining an interface, anyone can separate the implementation of a class from its behavior.
  • To provide multiple inheritances: Java doesn't support multiple inheritances of classes, but the developer can achieve a similar effect by using interfaces. A class can implement multiple interfaces, which allows it to inherit the behavior of all the interfaces it implements.
  • To define constants: Interfaces can be used to define constants that are shared by multiple classes.
  • To define callbacks: Interfaces can be used to define callbacks, which are methods that are called by an object in response to an event.
  • To achieve polymorphism: Interfaces can be used to achieve polymorphism, which is the ability of objects of different classes to be used interchangeably. By defining a common interface, the programmer can write code that works with any object that implements that interface.

How to declare an Interface in Java?

  • Interface declaration in Java is an interface that allows multiple inheritances of type.
  • It provides a powerful way of defining a contract between two classes, permitting loose coupling between the two parties.
  • Through interface declaration, complex relationships, such as inheritance and interface inheritances, may be established.
  • This helps create highly maintainable and extensible code that abstracts out major logic while avoiding deep nesting of classes.
  • Interface declaration also enables polymorphic behavior without the aggressive use of abstract classes or the need for extensive interface logic in the surrounding environment.
  • Interface declaration provides an efficient way to achieve flexibility in program development and code structure.

The relationship between classes and interfaces

  • The relationship between classes and interfaces in Java is an important concept to master when learning object-oriented programming.
  • Interfaces are basically contracts between a class and its implementers, that state which methods must be implemented within the class for it to be considered as fulfilling its obligation.
  • The interface defines what should happen, without getting into how it will be done.
  • This creates a layer of abstraction between the user and the developer, making the code easier to understand and maintain.
  • By separating data from its methods (encapsulating them in classes), software developers can create applications that best fit their particular requirements with far greater ease than if there were no such thing as interfaces.
  • In Java, classes implement interfaces in order to get specific behaviors or features that would otherwise not be available to them.
  • It's in this way that interfaces become so beneficial for object-oriented programming – they provide structure, simplify complexity, and ensure objects adhere to certain standards of behavior.

Nested Interface in Java

  • Nested interfaces in Java have multiple advantages and uses.
  • Nested interfaces are defined within another interface, and they can be used to group related aspects of a class together that have something in common.
  • Nested interfaces help create more logical class structures by decreasing the code needed.
  • Additionally, they allow developers to better encapsulate data and information, thus providing increased security against unauthorized modifications to code.
  • Nested interfaces offer improved scalability as well, allowing developers to work on larger projects like web applications without having all the code mixed up in one big file or class.
  • Nested interfaces are an important part of organizing and structuring coding projects when using Java, and their use can greatly enhance the efficiency of development efforts.

Summary

Using abstraction saves time and effort because it reduces the amount of code programmers have to use. It also provides real-world solutions that can help to improve the overall quality of an application by getting rid of redundant tasks and focusing on essential elements.

This type of abstraction does not require advanced knowledge and can be implemented with just a few simple lines of code. So, if you want to enhance your Java programming skills, don't forget to enroll in our Java Programming Course.

FAQs

Q1. What is an abstraction in Java?

Java's abstraction feature allows for the simplification of complex systems by modeling classes with key attributes.

Q2. What is the use of abstract classes in Java?

In Java, an abstract class serves as a template for other classes, allowing them to inherit common attributes and functions.

Q3. Why abstract class is required?

In order to facilitate code reuse and organization, abstract classes are necessary to establish a common interface for related classes.

Q4. What are the advantages of abstraction?

Code simplicity, enhanced maintainability, and explicit interfaces are benefits of abstraction.

Q5. What is the difference between abstraction and encapsulation?

Encapsulation deals with restricting access to data within a class, whereas abstraction focuses on providing high-level interfaces.

Share Article
Batches Schedule
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this