Interface vs Abstract Class in Java

Interface vs Abstract Class in Java

·

2 min read

Abstract Class

Abstract class permits you to make a functionality that subclasses can implement or override. Is a class that is declared abstract. It may or may not contain abstract methods. Abstract classes cannot be instantiated i.e

ClassOne one = new ClassOne();

e.g Sometimes we may come across a situation where we cannot provide implementation to all the methods in a class. We want to leave the implementation to a class that extends it. In such a case, we declare a class as abstract. To make a class abstract we use keyword abstract. Any class that contains one or more abstract methods is declared as abstract. If we don’t declare a class as abstract which contains abstract methods we get a compile-time error.

We can have any access to methods in abstract classes except for private ones. We cannot achieve multiple inheritance using abstract classes.

Important reasons for using abstraction

  1. Abstract classes offer default functionality for the subclasses.
  2. Provides a template for future specific classes
  3. Helps you to define a common interface for its subclasses
  4. Abstract class allows code reusability.

Abstract Class syntax

abstract class name {
//code
}

Code sample

abstract class Shape {
    int b = 20;
    abstract public void calculateArea();
}

public class Rectangle extends Shape {
    public static void main(String args[]) {
        Rectangle obj = new Rectangle();
        obj.b = 200;
        obj.calculateArea();
    }
    public void calculateArea() {
        System.out.println("Area is " + (b * b));
    }
}

Interface

An interface only permits you to state functionality but not to implement it. A class can extend only one abstract class while a class can implement multiple interfaces. The interface does not contain any concrete methods (methods that have code). All the methods of an interface are abstract methods. An interface cannot be instantiated. However, classes that implement interfaces can be instantiated.

Interface syntax

interface name{
//methods
}

Sample code

public interface TestOneAbstract {
    void printName();

    void printFavLanguage();
}

public class TestAbstract implements TestOneAbstract {

    @Override
    public void printName() {
        System.out.println("Name");
    }

    @Override
    public void printFavLanguage() {
        System.out.println("Java");
    }
}