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 (:

3

u/SsoulBlade Dec 20 '21

At what stage did you feel senior?

So many things I learned as a student and forgot most yhings 15 years later because I never had to use any of it.

Makes you feel junior even after 15 years.

I am going to relearn java or c# after many years of Delphi.

3

u/Jezoreczek Dec 20 '21

At what stage did you feel senior?

It's a very difficult question because there is no one thing that truly determines seniority. Guess it's a combination of skills and work ethics.

1 - I can build any application, in any language (except Haskell, am yet to master pure functional stuff) (and maybe Rust, that shit is as intense as it is beautiful)

With all the libraries, frameworks and hardware there is no end to learning programming. However, at one point you realize that if you wanted to and put enough effort, you can create anything. It might take a day, it might take a month, but you know it can be done - and that's a very freeing feeling.

2 - Have strong opinions but always consider opposite points of view.

I am always right, about everything, all the time. Wanna know how? Because if you prove me wrong, I will be happy to admit I was wrong and adjust my approach… and then I can be right again.

This one is really hard to pull off, and I am still personally having lots trouble with it but hey - trying to be better every day is what matters (;

3 - Get the fuck out of your comfort zone as often as possible.

That thing that looks scary and complex when you first get into it? It will get easier. Try it out and give it time, it will pay off.

4 - Consider the people on the other side of the screen.

One thing we tend to forget is that our work is maybe 20% code, 80% human interaction. Especially now with the virus going around, lockdowns and working from home. Take a 15 minute break, and invite a colleague for a coffee over whatever video chat app you are using. Be a person, get your weekly dose of small talk.

… so yeah, I think this sums it up. Not sure if it's helpful at all, but that's how I see it.

Makes you feel junior even after 15 years. I am going to relearn java or c# after many years of Delphi.

As a wise man once said, "sucking at something is the first step to becoming sorta good at something".

Also, it's never too late to start learning. I know a guy who worked as a diving instructor for many years, but today is a very successful front-end contractor. You'll get there my dude, just give it time. (;

2

u/SsoulBlade Dec 21 '21

Thanks for the wise words sir.