Java Abstract Classes vs. Interface

Quang Nguyen
Sep 3, 2018 · 2 min read

What are the differences between the two? Now that Java 8 enables default methods in interfaces, do you even need abstract classes at all?

Lets go over the attributes of an Abstract Class:

  • they may or may not include abstract methods
  • if a class includes abstract methods, then the class itself must be declared abstract

Now, similarities between Abstract Class and Interface:

  • can contain a mix of methods with or without implementation
  • both cannot be instantiated

Differences between the two:

Abstract Class:

  • can declare fields that are not static and final
  • can define public, protected, and private methods
  • can only extend one class ( for any class )

Interface:

  • all fields are automatically static and final
  • methods are automatically public
  • methods are implicitly abstract unless declared otherwise
  • can implement many interfaces

And when you should consider using each of them:

Abstract Class:

  • want to share code among closely related classes
  • expect a class that extends an abstract class to have many common fields and methods, or require access modifiers other than public
  • want to declare non-static and non-final fields. Also enables you to define methods that can access and modify the state of object to which they belong

Interface:

  • expect unrelated classes to implement the interface (e.g interface Comparable and Cloneable are implemented by many unrelated classes)
  • want to specify behavior but is not concern about who implements it
  • want to take advantage of multiple inheritance

Note that in code, “extends” comes before “implements” or else you will get a compiler error, e.g class A extends B implements C .

quangtn0018

Just my findings and techniques that I’ve learned from working and doing side projects on all things software engineering related

Quang Nguyen

Written by

Software Engineer

quangtn0018

Just my findings and techniques that I’ve learned from working and doing side projects on all things software engineering related

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade