r/javahelp • • Aug 25 '20

Abstract classes are useful in java 2020?

I've learned recently that with interfaces you are able to make default methods with custom modifiers and they work equal as abstract class default method.

In our cs class i was taught that abstract classes benefits were the implementation of defaults methods, but in modern versions of java, interfaces can do the same, while a class can implements multiple interfaces.

Is there something that abstract classes do that interfaces can't.

30 Upvotes

7 comments sorted by

32

u/gaveashow Aug 25 '20

Yes, abstract class can have instance fields.

Interfaces can't. That means that while they may have method implementations, all these methods can do is call other methods.

That's great for defining Collection's isEmpty() as size() == 0, or to automatically define stream() on anything that has iterator(). But, an interface cannot define any way to actually store its state, only rely on the fact that there are method implementations that do it right.

2

u/lethanhvn Aug 25 '20

Abstract class have some properties, interface havent't.

1

u/Yithar Intermediate Brewer Aug 25 '20

As stated, abstract classes have state that's not global. That's the difference between interfaces with default methods and abstract classes.

It gets a little bit murkier with mix-ins/traits in Scala (which are like interfaces but can have state; the Scala compiler actually creates separate Java classes for this in a process called linearization). But even then, there are 2 main reasons to use abstract classes over traits in Scala. I am bringing this up because it holds true for interfaces as well. Interfaces don't have constructors.

1

u/dionthorn this.isAPro=false; this.helping=true; Aug 27 '20

My games Entity Inheritance uses abstract classes all the way up to the Player and NonPlayerCharacter classes. In Character we introduce two interfaces implemented by character but not overridden until the top level Player and NPC classes.

https://github.com/dionthorn/2DTacticalRPG/wiki/1_Tutorial---Entity-Inheritance

0

u/[deleted] Aug 25 '20

[deleted]

4

u/Migeil Aug 25 '20

Interfaces: has a

That's composition. Implementing interfaces is still an "is a" relationship. You're giving your class a whole set of methods to define their behaviour.

1

u/HotRodLincoln Aug 25 '20

Agreed. Some things are to give information to other programmers.

Are variable names useful? It's functionally equivalent to just having a large array of Objects.

Is typing useful? It's just restricting how you can interact with Objects.

Are for loops useful? They're just while loops in a weird outfit. Are while loops useful? They're just very restrictive labels and gotos...