What is the difference between an interface and abstract class?

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

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

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

    I'd like to add one more difference which makes sense. For example, you have a framework with thousands of lines of code. Now if you want to add a new feature throughout the code using a method enhanceUI(), then it's better to add that method in abstract class rather in interface. Because, if you add this method in an interface then you should implement it in all the implemented class but it's not the case if you add the method in abstract class.

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

    Interfaces

    An interface is a contract: The person writing the interface says, "hey, I accept things looking that way", and the person using the interface says "OK, the class I write looks that way".

    An interface is an empty shell. There are only the signatures of the methods, which implies that the methods do not have a body. The interface can't do anything. It's just a pattern.

    For example (pseudo code):

    // I say all motor vehicles should look like this:
    interface MotorVehicle
    {
        void run();
    
        int getFuel();
    }
    
    // My team mate complies and writes vehicle looking that way
    class Car implements MotorVehicle
    {
    
        int fuel;
    
        void run()
        {
            print("Wrroooooooom");
        }
    
    
        int getFuel()
        {
            return this.fuel;
        }
    }
    

    Implementing an interface consumes very little CPU, because it's not a class, just a bunch of names, and therefore there isn't any expensive look-up to do. It's great when it matters, such as in embedded devices.


    Abstract classes

    Abstract classes, unlike interfaces, are classes. They are more expensive to use, because there is a look-up to do when you inherit from them.

    Abstract classes look a lot like interfaces, but they have something more: You can define a behavior for them. It's more about a person saying, "these classes should look like that, and they have that in common, so fill in the blanks!".

    For example:

    // I say all motor vehicles should look like this:
    abstract class MotorVehicle
    {
    
        int fuel;
    
        // They ALL have fuel, so lets implement this for everybody.
        int getFuel()
        {
             return this.fuel;
        }
    
        // That can be very different, force them to provide their
        // own implementation.
        abstract void run();
    }
    
    // My teammate complies and writes vehicle looking that way
    class Car extends MotorVehicle
    {
        void run()
        {
            print("Wrroooooooom");
        }
    }
    

    Implementation

    While abstract classes and interfaces are supposed to be different concepts, the implementations make that statement sometimes untrue. Sometimes, they are not even what you think they are.

    In Java, this rule is strongly enforced, while in PHP, interfaces are abstract classes with no method declared.

    In Python, abstract classes are more a programming trick you can get from the ABC module and is actually using metaclasses, and therefore classes. And interfaces are more related to duck typing in this language and it's a mix between conventions and special methods that call descriptors (the __method__ methods).

    As usual with programming, there is theory, practice, and practice in another language :-)

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

    Interface: Turn ( Turn Left, Turn Right.)

    Abstract Class: Wheel.

    Class: Steering Wheel, derives from Wheel, exposes Interface Turn

    One is for categorizing behavior that can be offered across a diverse range of things, the other is for modelling an ontology of things.

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

    Inheritance is used for two purposes:

    • To allow an object to regard parent-type data members and method implementations as its own.

    • To allow a reference to an objects of one type to be used by code which expects a reference to supertype object.

    In languages/frameworks which support generalized multiple inheritance, there is often little need to classify a type as either being an "interface" or an "abstract class". Popular languages and frameworks, however, will allow a type to regard one other type's data members or method implementations as its own even though they allow a type to be substitutable for an arbitrary number of other types.

    Abstract classes may have data members and method implementations, but can only be inherited by classes which don't inherit from any other classes. Interfaces put almost no restrictions on the types which implement them, but cannot include any data members or method implementations.

    There are times when it's useful for types to be substitutable for many different things; there are other times when it's useful for objects to regard parent-type data members and method implementations as their own. Making a distinction between interfaces and abstract classes allows each of those abilities to be used in cases where it is most relevant.

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

    I am constructing a building of 300 floors

    The building's blueprint interface

    • For example, Servlet(I)

    Building constructed up to 200 floors - partially completed---abstract

    • Partial implementation, for example, generic and HTTP servlet

    Building construction completed-concrete

    • Full implementation, for example, own servlet

    Interface

    • We don't know anything about implementation, just requirements. We can go for an interface.
    • Every method is public and abstract by default
    • It is a 100% pure abstract class
    • If we declare public we cannot declare private and protected
    • If we declare abstract we cannot declare final, static, synchronized, strictfp and native
    • Every interface has public, static and final
    • Serialization and transient is not applicable, because we can't create an instance for in interface
    • Non-volatile because it is final
    • Every variable is static
    • When we declare a variable inside an interface we need to initialize variables while declaring
    • Instance and static block not allowed

    Abstract

    • Partial implementation
    • It has an abstract method. An addition, it uses concrete
    • No restriction for abstract class method modifiers
    • No restriction for abstract class variable modifiers
    • We cannot declare other modifiers except abstract
    • No restriction to initialize variables

    Taken from DurgaJobs Website

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

    Differences between abstract class and interface on behalf of real implementation.

    Interface: It is a keyword and it is used to define the template or blue print of an object and it forces all the sub classes would follow the same prototype,as for as implementation, all the sub classes are free to implement the functionality as per it's requirement.

    Some of other use cases where we should use interface.

    Communication between two external objects(Third party integration in our application) done through Interface here Interface works as Contract.

    Abstract Class: Abstract,it is a keyword and when we use this keyword before any class then it becomes abstract class.It is mainly used when we need to define the template as well as some default functionality of an object that is followed by all the sub classes and this way it removes the redundant code and one more use cases where we can use abstract class, such as we want no other classes can directly instantiate an object of the class, only derived classes can use the functionality.

    Example of Abstract Class:

     public abstract class DesireCar
      {
    
     //It is an abstract method that defines the prototype.
         public abstract void Color();
    
      // It is a default implementation of a Wheel method as all the desire cars have the same no. of wheels.   
     // and hence no need to define this in all the sub classes in this way it saves the code duplicasy     
    
      public void Wheel() {          
    
                   Console.WriteLine("Car has four wheel");
                    }
               }
    
    
        **Here is the sub classes:**
    
         public class DesireCar1 : DesireCar
            {
                public override void Color()
                {
                    Console.WriteLine("This is a red color Desire car");
                }
            }
    
            public class DesireCar2 : DesireCar
            {
                public override void Color()
                {
                    Console.WriteLine("This is a red white Desire car");
                }
            }
    

    Example Of Interface:

      public interface IShape
            {
              // Defines the prototype(template) 
                void Draw();
            }
    
    
      // All the sub classes follow the same template but implementation can be different.
    
        public class Circle : IShape
        {
            public void Draw()
            {
                Console.WriteLine("This is a Circle");
            }
        }
    
        public class Rectangle : IShape
        {
            public void Draw()
            {
                Console.WriteLine("This is a Rectangle");
            }
        }
    
    0 讨论(0)
提交回复
热议问题