DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

SBOMs are essential to circumventing software supply chain attacks, and they provide visibility into various software components.

Related

  • Advanced Brain-Computer Interfaces With Java
  • Simplify Java: Reducing Unnecessary Layers and Interfaces [Video]
  • Java 21 SequenceCollection: Unleash the Power of Ordered Collections
  • Projections/DTOs in Spring Data R2DBC

Trending

  • Self-Supervised Learning Techniques
  • Building an AI Nutrition Coach With OpenAI, Gradio, and gTTS
  • Stabilizing ETL Pipelines With Airflow, Presto, and Metadata Contracts
  • What Is Plagiarism? How to Avoid It and Cite Sources
  1. DZone
  2. Coding
  3. Java
  4. Java: Interface vs. Abstract Class

Java: Interface vs. Abstract Class

How to characterize concrete classes using abstract classes and interfaces in Java.

By 
Daniel Meyer user avatar
Daniel Meyer
·
Mar. 14, 17 · Opinion
Likes (32)
Comment
Save
Tweet
Share
63.8K Views

Join the DZone community and get the full member experience.

Join For Free

Preface

A class is named a concrete class when it has a name and implements every remaining method that is declared along the class hierarchy. Along with the hierarchy, its supertypes become a more general representation of the acting domain, and finally goes beyond that border and ends with the fact that almost everything is an object. A supertype can be either a concrete class that is apparently not final, an abstract class or even one or more interfaces. Combining a super or an abstract class with some interfaces is also a wide acknowledged way for characterizing a concrete class. Polymorphism is given when more than one class implements a particular method differently based on a class’s nature. In this article, the focus is on two of three kinds of supertypes they distinguish from their essential characteristics. Both an interface as well as an abstract class can be instantiated in a manner of an anonymous class.

Abstract Class

Typically, an abstract class implements common behaviors and member variables across any concrete class, and its method might have already specified an interface. The distinguishable behavior is gained through declaring abstract methods, which need to be implemented in a specific class. The abstract class can inherit features from another concrete or abstract class, and can enrich further behavior while adding interfaces. In Java, such tangible implementations can be explicitly emphasized with the annotation @Override that indicates a deviation of manner (docs.oracle.org, n.d.). The polymorphism stops at that point, where a concrete implementation of a method becomes final. As methods in an abstract class can also be private, it makes such a class most appropriate for encapsulating private methods while breaking down the complexity of shared methods into smaller pieces. (Martin, 2009). An abstract class is ultimately very close to a concrete implementation.

Interface

Since Java 1.8, an interface can implement default methods to provide a general behavior (Panka, 2016). Consequently, both an abstract class and an interface approach each other regarding their features. While member variables of an interface are explicitly public and final, an abstract class does not sanction their members about access modifiers. Moreover, there is a small difference with a significant effect regarding possible access modifiers for a default method in interfaces. A default method is always public and is in contrast to an abstract method that accepts either default, protected, or public as an access modifier. Whatever an interface defines, it can be used anywhere and may enrich an object with specific behaviors. An interface allows only inheritance from another interface. Both an abstract class and an interface can implement static methods. (docs.oracle.com, n.d.). Another type of interfaces are such without any declared method and are fully accepted as a marker interface. They merely indicate the compliance from a developer that, for example, a class is serializable (java.io.Serializable) or cloneable (java.lang.Cloneable) (mrbool.com, n.d.).

Example 1: Interface vs. Abstract Class

This comparison emphasizes the advantage of an abstract class over an interface focused on the calculation of the angle between two straight lines. However, both an interface and an abstract class can be used for that purpose while the first does not go in line with Martin’s suggestions about clean code.

public interface TwoDimensional {
    double PI = 3.141579; //is public and final

    default double getAngle(TwoDimensional a, TwoDimensional b) /* is public */{
        double alpha = 0.0;
        //do complex calculation here
        //modulus
        //scalar
        //to degrees
        return alpha;
    }

    int getX(); //is public

    int getY();
}


public abstract class AbstractTwoDimensional {
    public final double PI = 3.141579;
    private int x;
    private int y;

    public final double getAngle(AbstractTwoDimensional other) {
        double a = calcModulus(x, y);
        double b = calcModulus(other.getX(), other.getY());
        double s = scalar(other.getX(), other.getY());
        return toDegrees(s, a, b);
    }

    private double toDegrees(double s, double a, double b) {
        //compute
        return 0;
    }

    private double calcModulus(int x, int y) {
        //compute...
        return 0;
    }

    private double scalar(int x2, int y2) {
        //compute...
        return 0;
    }

    abstract int getX();

    abstract int getY();

    //some other abstract methods…

}


Example 2: Combination of Interface and Abstract Class

This example is very close to the prior one, but is distinguished by a mix of interface and abstract classes. They both characterize concrete classes.

public interface TwoDimensional {
    Double PI = 3.141579;

    double getAngle(TwoDimensional other);

    int getX();

    int getY();
}


public abstract class AbstractTwoDimensional implements TwoDimensional {    
    private int x;
    private int y;

    @Override
    public final double getAngle(TwoDimensional other) {
        double a = calcModulus(x, y);
        double b = calcModulus(other.getX(), other.getY());
        double s = scalar(other.getX(), other.getY());
        return toDegrees(s, a, b);
    }

    @Override
    public final int getX() {
        return x;
    }

    @Override
    public final int getY() {
        return y;
    }

    protected void setX(int x) {
        this.x = x;
    }

    protected void setY(int y) {
        this.y = y;
    }

    private double toDegrees(double s, double a, double b) {
        //compute
        return 0;
    }

    private double calcModulus(int x, int y) {
        //compute...
        return 0;
    }

    private double scalar(int x2, int y2) {
        //compute...
        return 0;
    }
}


public class MutableLine extends AbstractTwoDimensional {

    //some specific things…

    public MutableLine(ImmutableLine line) {
        //extract data and init
    }

}


public final class ImmutableLine extends AbstractTwoDimensional {
    //some specific things...

    public ImmutableLine(MutableLine line) {
        //extract data
    }

    @Override
    public final void setX(int x) {
        //throw an appropriate exception
    }

    @Override
    public final void setY(int y) {
        //throw an appropriate exception
    }
}

References

docs.oracle.org (n.d.) Anonymous Classes. Oracle. Available from: https://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html. [9 February 2017].

docs.oracle.org (n.d.) Overriding and Hiding Methods. Oracle. Available from: https://docs.oracle.com/javase/tutorial/java/IandI/override.html. [10 February 2017].

Martin, R. C. (2009) Clean Code: A Handbook of Agile Software Craftsmanship. Prentice Hall. [Kindle]. [11 February 2017].

Panka, J. (2016) Java 8 Interface Changes – static method, default method. JournalDev. Available from: http://www.journaldev.com/2752/java-8-interface-changes-static-method-default-method. [9 February 2017].

docs.oracle.com (n.d.) Lesson: Interfaces and Inheritance. Available from: https://docs.oracle.com/javase/tutorial/java/IandI. [10 February 2017].

mrbool.com (n.d.) What is Marker interface in Java? Available from: http://mrbool.com/what-is-marker-interface-in-java/28557. [11 February 2017].



Interface (computing) Java (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • Advanced Brain-Computer Interfaces With Java
  • Simplify Java: Reducing Unnecessary Layers and Interfaces [Video]
  • Java 21 SequenceCollection: Unleash the Power of Ordered Collections
  • Projections/DTOs in Spring Data R2DBC

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • [email protected]

Let's be friends: