waltcow / blog

A personal blog
21 stars 2 forks source link

Interface vs Abstract Class in Java #51

Open waltcow opened 4 years ago

waltcow commented 4 years ago

What is Interface?

The interface is a blueprint that can be used to implement a class. 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. Interfaces never contain instance variables but, they can contain public static final variables (i.e., constant class variables)

What Is Abstract Class?

A class which has the abstract keyword in its declaration is called abstract class. Abstract classes should have at least one abstract method. , i.e., methods without a body. It can have multiple concrete methods.

Abstract classes allow you to create blueprints for concrete classes. But the inheriting class should implement the abstract method.

Abstract classes cannot be instantiated.

Important Reasons For Using Interfaces

Abstract classes offer default functionality for the subclasses.

Interface Vs. Abstract Class

An abstract class permits you to make functionality that subclasses can implement or override whereas 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.

//Interface Syntax

interface name{
//methods
}

//Java Interface Example:

interface Pet {
    public void test();
}
class Dog implements Pet {
    public void test() {
        System.out.println("Interface Method Implemented");
    }
    public static void main(String args[]) {
        Pet p = new Dog();
        p.test();
    }
}
//Abstract Class Syntax

abstract class name{
    // code
}

//Abstract class example:

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 " + (obj.b * obj.b));
    }
}