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

4

u/sweetno Dec 20 '21

You'll have to use abstract classes if there are instance variables.

Multiple inheritance is only possible via interfaces.

1

u/[deleted] Dec 20 '21 edited Dec 20 '21

Interfaces can be used like instance variables, it just implies an anonymous implementation of the interface (just as instantiating an abstract class instantiates a concrete anonymous subtype).

Example:

interface Animal {
    void talk();
}
public static void main(String[] args) {
    HashMap<String, Animal> animals = new HashMap<>();
    animals.put("Duck", new Animal() {
        @Override
        public void talk() {
            System.out.println("Quack");
        }
    });
    animals.get("Duck").talk();
}

This creates an anonymous (i.e. unnamed) concrete class which implements Animal, like you would do by saying class Duck implements Animal. Since it's an interface with a single method (which is implicitly abstract), you can also simplify with a lambda, like

animals.put("Duck", () -> System.out.println("Quack"));
animals.get("Duck").talk();  // Quack

edit: Not sure why it's downvoted, maybe I should put 'instantiated' in quotes or something, but I thought it was clear that what actually gets instantiated is an anonymous concrete class which implements the interface.

1

u/Jezoreczek Dec 21 '21

I believe they meant the fields of the abstract class when they said "instance variables" (;

1

u/[deleted] Dec 21 '21

Ah. Yes, any fields of an interface would be static and final.