What is the difference between an interface and abstract class?

前端 未结 30 1815
情歌与酒
情歌与酒 2020-11-21 11:51

What exactly is the difference between an interface and abstract class?

相关标签:
30条回答
  • 2020-11-21 12:13

    The comparison of interface vs. abstract class is wrong. There should be two other comparisons instead: 1) interface vs. class and 2) abstract vs. final class.

    Interface vs Class

    Interface is a contract between two objects. E.g., I'm a Postman and you're a Package to deliver. I expect you to know your delivery address. When someone gives me a Package, it has to know its delivery address:

    interface Package {
      String address();
    }
    

    Class is a group of objects that obey the contract. E.g., I'm a box from "Box" group and I obey the contract required by the Postman. At the same time I obey other contracts:

    class Box implements Package, Property {
      @Override
      String address() {
        return "5th Street, New York, NY";
      }
      @Override
      Human owner() {
        // this method is part of another contract
      }
    }
    

    Abstract vs Final

    Abstract class is a group of incomplete objects. They can't be used, because they miss some parts. E.g., I'm an abstract GPS-aware box - I know how to check my position on the map:

    abstract class GpsBox implements Package {
      @Override
      public abstract String address();
      protected Coordinates whereAmI() {
        // connect to GPS and return my current position
      }
    }
    

    This class, if inherited/extended by another class, can be very useful. But by itself - it is useless, since it can't have objects. Abstract classes can be building elements of final classes.

    Final class is a group of complete objects, which can be used, but can't be modified. They know exactly how to work and what to do. E.g., I'm a Box that always goes to the address specified during its construction:

    final class DirectBox implements Package {
      private final String to;
      public DirectBox(String addr) {
        this.to = addr;
      }
      @Override
      public String address() {
        return this.to;
      }
    }
    

    In most languages, like Java or C++, it is possible to have just a class, neither abstract nor final. Such a class can be inherited and can be instantiated. I don't think this is strictly in line with object-oriented paradigm, though.

    Again, comparing interfaces with abstract classes is not correct.

    0 讨论(0)
  • 2020-11-21 12:13

    The only difference is that one can participate in multiple inheritance and other cannot.

    The definition of an interface has changed over time. Do you think an interface just has method declarations only and are just contracts? What about static final variables and what about default definitions after Java 8?

    Interfaces were introduced to Java because of the diamond problem with multiple inheritance and that's what they actually intend to do.

    Interfaces are the constructs that were created to get away with the multiple inheritance problem and can have abstract methods, default definitions and static final variables.

    See Why does Java allow static final variables in interfaces when they are only intended to be contracts?.

    0 讨论(0)
  • 2020-11-21 12:15

    An abstract class is a class whose object cannot be created or a class which cannot be instantiated. An abstract method makes a class abstract. An abstract class needs to be inherited in order to override the methods that are declared in the abstract class. No restriction on access specifiers. An abstract class can have constructor and other concrete(non abstarct methods ) methods in them but interface cannot have.

    An interface is a blueprint/template of methods.(eg. A house on a paper is given(interface house) and different architects will use their ideas to build it(the classes of architects implementing the house interface) . It is a collection of abstract methods , default methods , static methods , final variables and nested classes. All members will be either final or public , protected and private access specifiers are not allowed.No object creation is allowed. A class has to be made in order to use the implementing interface and also to override the abstract method declared in the interface. An interface is a good example of loose coupling(dynamic polymorphism/dynamic binding) An interface implements polymorphism and abstraction.It tells what to do but how to do is defined by the implementing class. For Eg. There's a car company and it wants that some features to be same for all the car it is manufacturing so for that the company would be making an interface vehicle which will have those features and different classes of car(like Maruti Suzkhi , Maruti 800) will override those features(functions).

    Why interface when we already have abstract class? Java supports only multilevel and hierarchal inheritance but with the help of interface we can implement multiple inheritance.

    0 讨论(0)
  • 2020-11-21 12:15

    I am 10 yrs late to the party but would like to attempt any way. Wrote a post about the same on medium few days back. Thought of posting it here.

    tl;dr; When you see “Is A” relationship use inheritance/abstract class. when you see “has a” relationship create member variables. When you see “relies on external provider” implement (not inherit) an interface.

    Interview Question: What is the difference between an interface and an abstract class? And how do you decide when to use what? I mostly get one or all of the below answers: Answer 1: You cannot create an object of abstract class and interfaces.

    ZK (That’s my initials): You cannot create an object of either. So this is not a difference. This is a similarity between an interface and an abstract class. Counter Question: Why can’t you create an object of abstract class or interface?

    Answer 2: Abstract classes can have a function body as partial/default implementation.

    ZK: Counter Question: So if I change it to a pure abstract class, marking all the virtual functions as abstract and provide no default implementation for any virtual function. Would that make abstract classes and interfaces the same? And could they be used interchangeably after that?

    Answer 3: Interfaces allow multi-inheritance and abstract classes don’t.

    ZK: Counter Question: Do you really inherit from an interface? or do you just implement an interface and, inherit from an abstract class? What’s the difference between implementing and inheriting? These counter questions throw candidates off and make most scratch their heads or just pass to the next question. That makes me think people need help with these basic building blocks of Object-Oriented Programming. The answer to the original question and all the counter questions is found in the English language and the UML. You must know at least below to understand these two constructs better.

    Common Noun: A common noun is a name given “in common” to things of the same class or kind. For e.g. fruits, animals, city, car etc.

    Proper Noun: A proper noun is the name of an object, place or thing. Apple, Cat, New York, Honda Accord etc.

    Car is a Common Noun. And Honda Accord is a Proper Noun, and probably a Composit Proper noun, a proper noun made using two nouns.

    Coming to the UML Part. You should be familiar with below relationships:

    • Is A
    • Has A
    • Uses

    Let’s consider the below two sentences. - HondaAccord Is A Car? - HondaAccord Has A Car?

    Which one sounds correct? Plain English and comprehension. HondaAccord and Cars share an “Is A” relationship. Honda accord doesn’t have a car in it. It “is a” car. Honda Accord “has a” music player in it.

    When two entities share the “Is A” relationship it’s a better candidate for inheritance. And Has a relationship is a better candidate for creating member variables. With this established our code looks like this:

    abstract class Car
    {
       string color;
       int speed;
    }
    class HondaAccord : Car
    {
       MusicPlayer musicPlayer;
    }
    

    Now Honda doesn't manufacture music players. Or at least it’s not their main business.

    So they reach out to other companies and sign a contract. If you receive power here and the output signal on these two wires it’ll play just fine on these speakers.

    This makes Music Player a perfect candidate for an interface. You don’t care who provides support for it as long as the connections work just fine.

    You can replace the MusicPlayer of LG with Sony or the other way. And it won’t change a thing in Honda Accord.

    Why can’t you create an object of abstract classes?

    Because you can’t walk into a showroom and say give me a car. You’ll have to provide a proper noun. What car? Probably a honda accord. And that’s when a sales agent could get you something.

    Why can’t you create an object of an interface? Because you can’t walk into a showroom and say give me a contract of music player. It won’t help. Interfaces sit between consumers and providers just to facilitate an agreement. What will you do with a copy of the agreement? It won’t play music.

    Why do interfaces allow multiple inheritance?

    Interfaces are not inherited. Interfaces are implemented. The interface is a candidate for interaction with the external world. Honda Accord has an interface for refueling. It has interfaces for inflating tires. And the same hose that is used to inflate a football. So the new code will look like below:

    abstract class Car
    {
        string color;
        int speed;
    }
    class HondaAccord : Car, IInflateAir, IRefueling
    {
        MusicPlayer musicPlayer;
    }
    

    And the English will read like this “Honda Accord is a Car that supports inflating tire and refueling”.

    0 讨论(0)
  • 2020-11-21 12:16

    I don't want to highlight the differences, which have been already said in many answers ( regarding public static final modifiers for variables in interface & support for protected, private methods in abstract classes)

    In simple terms, I would like to say:

    interface: To implement a contract by multiple unrelated objects

    abstract class: To implement the same or different behaviour among multiple related objects

    From the Oracle documentation

    Consider using abstract classes if :

    1. You want to share code among several closely related classes.
    2. You expect that classes that extend your abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private).
    3. You want to declare non-static or non-final fields.

    Consider using interfaces if :

    1. You expect that unrelated classes would implement your interface. For example,many unrelated objects can implement Serializable interface.
    2. You want to specify the behaviour of a particular data type, but not concerned about who implements its behaviour.
    3. You want to take advantage of multiple inheritance of type.

    abstract class establishes "is a" relation with concrete classes. interface provides "has a" capability for classes.

    If you are looking for Java as programming language, here are a few more updates:

    Java 8 has reduced the gap between interface and abstract classes to some extent by providing a default method feature. An interface does not have an implementation for a method is no longer valid now.

    Refer to this documentation page for more details.

    Have a look at this SE question for code examples to understand better.

    How should I have explained the difference between an Interface and an Abstract class?

    0 讨论(0)
  • 2020-11-21 12:16

    We have various structural/syntactical difference between interface and abstract class. Some more differences are

    [1] Scenario based difference:

    Abstract classes are used in scenarios when we want to restrict the user to create object of parent class AND we believe there will be more abstract methods will be added in future.

    Interface has to be used when we are sure there can be no more abstract method left to be provided. Then only an interface is published.

    [2] Conceptual difference:

    "Do we need to provide more abstract methods in future" if YES make it abstract class and if NO make it Interface.

    (Most appropriate and valid till java 1.7)

    0 讨论(0)
提交回复
热议问题