3. Interface & Abstract Class

Vegeedog
JavaNotes
Published in
2 min readJul 13, 2021

--

Interface

To create an interface, we use the same way as we created a class. Just right click on the package →”New” →”Java Class” →”Interface”

For instance, we create an interface named “CarInterface.”

Note:

  • One can only define “abstract” methods in interface, which means that the methods cannot have bodies.
  • All the abstract methods must be public! So we do not need to specifically state that they are public, because they have to be so.

To have class based on this interface, we use the keyword “implements”.

And the class need to implement all the methods defined in the interface.

For instance, we create a “ElectricCar” class based on “CarInterface”

We can self define some fields in this class, and also the constructors and getters & setters.

But most importantly, we need to implement the methods of the interface, which is the “start” and “move” methods.

To do this, we use the shortcut: Ctrl + I

Also, a class can implement multiple interfaces.

implement two interfaces

Abstract Class

We can define an abstract base class, and create other classes to inherit it. The concept is quite similar to interface.

For instance, we can define an abstract class named “TestAbstractClass”

Note that, we can have both abstract and non-abstract methods in an abstract class, whereas interface can only contain abstract methods. Also, we can actually define private & non-abstract methods here, yet these kind of methods cannot be override later.

To inherit this abstract class, we use the keyword: “extends”

For instance, create “TestClass” to inherit “TestAbstractClass”.

To implement the base class methods, we use the shortcut: Ctrl + O

Note:

  • If we override methods that already have a body, then it would assume that you may want to use the body as well. Hence, the “super” keyword stands for this body in the base class. (Same as the “base” keyword in C++)
  • Private & non-abstract methods cannot be override.
  • Cannot inherit multiple abstract classes.

Conclusion:

Interface vs. Abstract Class

--

--