Question

Given the provision of default and static methods new possibilities in interfaces, could someone help with use cases that might still warrant me to want to use Abstract Classes for inheritance hierarchy of common behaviors?

Normally, I would have:

public interface Shape
{
    void draw();
}

With a hierarchy class like so:

public abstract class Triangle implements Shape
{
    public void sayMyCategory(String name)
    {
        System.out.println(name);
    }
}

And then have:

public class RightAngleTriangle extends Triangle
{   
    public void draw()
    {       
        System.out.println("Right Angle Triangle Drawn");
    }
}



With Java 8, I only need to have:

public interface ShapeImpr
{   
    void draw();

    public default void sayMyCategory(String name)
    {
        System.out.println(name);
    }
}

And then:

public class RightAngleTriangleImprv implements ShapeImpr
{   
    public void draw()
    {
        System.out.println("Right Angle Triangle Drawn");
    }       
}
Was it helpful?

Solution 2

There is a reduced need for abstract classes as some things that previously you needed them for can now be done by interfaces.

However abstract classes still can do things that interfaces cannot. For example containing member variables.

A simple example would be an interface that specifies listeners (addListener, removeListener, notifyListeners). The interface cannot provide a default implementation of those methods, however you can provide an abstract class which does.

You can also define things like protected methods in an abstract class which the people using the abstract class have to implement but which are not published as part of the public API.

OTHER TIPS

Abstract class can define non-public methods, which is obviously not possible in interface.

The new features of java 8 are there to enable some behaviours we previously used interfaces for. Abstract classes are a structural concept. You use them to implement the IS-A relationship between classes in a class hierarchy.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top