Is there a time when you use Interface instead of an abstract class? And is there the opposite?

Asked 2 years ago, Updated 2 years ago, 110 views

It's a general OOP question. I want to make a general comparison between Interface and the basic use of abstraction classes. I want to know the difference between using the interface and using the abstract class!

oop java inheritance interface abstract-class

2022-09-22 22:24

2 Answers

Abstract classes can share states or functions. The interface only serves to provide status or functionality. I mean, an abstract class is an abstract class if you have any abstract method. So it's possible to implement the method in an abstract class. The interface, on the other hand, provides only form without implementation, and the implementation must be done in the inherited class.

A good abstract class can share features or states, reducing the amount of code that needs to be rewritten.


2022-09-22 22:24

If you take Bulgogi's explanation as an example,

The abstract class can pre-implement the method like Bird below.

abstract class Bird{
        abstract void sing();

        void fly(){
            System.out.println ("Flying")
        }
    }

class Duck extends Bird{
        @Override
        void sing() {
            System.out.println ("quack!!");
        }
    }

To make this an interface, all implementations must be done by Duck. It's different that we can't implement a common method like fly in advance.

interface Bird{
        void sing();
        void fly();
    }

class Duck implements Bird{
        void fly(){
            System.out.println ("Flying")
        }

        void sing() {
            System.out.println ("quack!!");
        }
    }


2022-09-22 22:24

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.