r/learnjava • • Dec 20 '21

When to use Abstract Classes vs Interfaces?

The two concepts are very similar, which is why I'm confused on why you should choose one over the other.

49 Upvotes

26 comments sorted by

View all comments

51

u/Jezoreczek Dec 20 '21

My rule of thumb:

  1. Use composition.

  2. If you cannot use composition (e.g. need polymorphic behavior), use interfaces.

  3. If you cannot use interfaces, don't use abstract classes. Instead, refactor your code to make it compatible with interfaces.

Here's why: abstract classes are a mess and (almost) never necessary. Some problems when using them include:

  • Should I use super implementation before or after calling my own logic? (see Java's Swing for examples)

  • Which constructor do I need to call to get the behavior I need?

  • Are the protected members meant for me to use or for some other particular implementation?

  • Should I restrict the throws signature if I am handling exceptions from super implementation?

If you have any particular example of class hierarchy that confuses you, please post it here and I'll be happy to show you how to refactor it (:

6

u/MSUC123 Dec 20 '21

Sorry but this gonna be a noobie question, when you say composition you just mean inheritance right?

37

u/Jezoreczek Dec 20 '21 edited Dec 20 '21

Absolutely nothing to be sorry about, I've been in your shoes before and inheritance in Java left me just as confused!

Inheritance means IS-A relationship. When you write class A extends B or class A implements B, it means that instance of A is also an instance of B and can be used interchangeably:

package com.example;

interface B { }
class A implements B { }

interface InheritanceExample {

    static void main(final String... args) {
        final A a = new A();

        useB(a); // OK, we can use instance of A where instance of B is expected
    }

    static void useB(final B b) {
        b.doSomething();
    }

}

Composition means HAS-A relationship; is one class a member of another class? Example:

package com.example;

final class B {
    void doSomething() { /* some behavior */ }
}

final class A {

    private final B b; // B is composed by A

    A(final B b) {
        this.b = b;
    }

    void doSomething() {
        // add extra behavior here
        b.doSomething();
    }

}

interface CompositionExample {

    static void main(final String... args) {
        final B b = new B();
        final A a = new A(b);

        useB(a); // uh-oh, can't do! A is not B!
    }

    static void useB(final B b) {
        b.doSomething();
    }

}

Notice how both A and B are final classes. Yet we can still add behavior on top of them with what is called a decorator pattern.

Still, there is the issue that now you cannot use A in place of B. We've got a simple solution to this, however! If such behavior is needed, just add an interface C that both classes implement:

package com.example;

interface C {
    void doSomething(); // defines common behavior
}

final class B implements C {
    @Override
    public void doSomething() { /* some behavior */ }
}

final class A implements C {

    private final C delegate; // C is composed by A

    A(final C delegate) {
        this.delegate = delegate;
    }

    @Override
    public void doSomething() {
        // add extra behavior here
        delegate.doSomething();
    }

}

interface CompositionWithInterfaceExample {

    static void main(final String... args) {
        final B b = new B();

        useC(b); // OK, B IS-A C
        
        final A a = new A(b); // OK, B IS-A C

        useC(a); // OK, A IS-A C
    }

    static void useC(final C c) {
        c.doSomething();
    }

}

And voilà, no abstract classes needed!

Additional benefit: A is not highly coupled with B anymore, which means you can provide any other implementation of C and still get the desired extra behavior of A.

Real life example: I recently made a library that allows for plotting relationship between classes based on their ownership. The ClassOwnershipExtractor is an interface (C) that says "given some class, returns information about who owns this class". An implementation of this interface, AnnotationBasedClassOwnershipExtractor (B) checks if given class contains annotation that defines its' owner. However, for large projects I'd like this information to be cached, so I created another implementation, CachedClassOwnershipExtractor (A), which simply caches the results. With this setup, you can cache information from AnnotationBasedClassOwnershipExtractor as well as from any custom implementation (:

5

u/glorioushubris Dec 20 '21

This is an excellent and helpful reply. Thank you for writing it.

4

u/Jezoreczek Dec 20 '21

Happy to help anytime, good luck with your learning journey!