[Java core] – Abstract class and Interface

Have you ever wondered why they had to create both ‘Abstract class’ and ‘Interface’? I have, since I first learned about it. The reason is they have many things in common. For example, you can initiate an abstract method in both an Abstract class or Interface and then extends or implements it.

So in today post, I’ll discuss both abstract class and interface, then advise you when and how to use each of those correctly.

1. ABSTRACT CLASS

Remember, Java only has single inheritance, so one class can only extend one class. In an abstract class. you can:
– declare 0, 1 or more abstract methods.
– declare 0, 1 or more normal methods.
– NOT initiate an object directly.


And when a class has at least one abstract method, that class must be abstract.

public abstract class Abc {
    public abstract void doSomething();  // abstract method without body
    public abstract String doNothing();  // abstract method without body
    public int returnTwo() {
        return 2;
    }   // a normal method with body
}

When a class extends an abstract class, it must override all abstract methods in the abstract class to use.

2. INTERFACE

An interface is a ‘pure’ abstract class, but it only provides a form – NO implementation (while abstract class can implement a method within it).
To make a class that conforms to a particular interface, we can use the implements keyword.
All methods in interface public by default.

A class can implements one or more interfaces. Similarly, an interface can extend one or more interfaces, too, but interfaces cannot extend classes.

public interface Move {
    public abstract void run();
    void crawl();
    // all methods in an interface is public abstract, so if you didn't specify it, Java would still understand it is 'public abstract'.
}

A comparison table can help you a lot.

InterfaceAbstract Class
Cannot provide any method implementationCan provide complete method implementation
A class can implement one or more interfaces.A class can extend only one class/ abstract class
Variables are public, static and final (const)Methods can be used to initialise variables
Methods are public and abstractMethods can be public/default/protected or even private. New method implementations may be added.
Can be used to unify two disparate classesForces relationship between subclasses.

Happy coding!!!

 

Leave a Reply

Your email address will not be published. Required fields are marked *