Can you help me understand in a practical example the usage abstract classes vs interfaces?

前端 未结 9 607
孤城傲影
孤城傲影 2020-12-24 04:09

Can you give me an almost overly simplistic understanding of abstract class vs inheritance use and help me so I can truly understand the concept and how to implement? I have

相关标签:
9条回答
  • 2020-12-24 04:31

    To be honest it scares me the amount of people in the industry that don't know this regardless of whether it is a homework question or not. Therefore I will answer.

    Interfaces abstract implementation and so do abstract classes. There is no "vs" because you can create an abstract class that implements an interface too. So don't think they're at war with one another.

    Therefore EITHER can be used when you don't want the consumer to know too much about the implementation. An interface is a bit better at this job because it has no implementation, it just states what buttons the consumer can press the values they get back and send where an abstract class may state a bit more than this (or even a lot more!). So if you just take this point onboard you only really need interfaces. Ergo, point two:

    As abstract class is used when you want to share common code between two different implementations of an interface. In this scenario two concrete implementations both inherit from the abstract class which implements the interface.

    Simple example is IDataStore. SavingToATextFile datastore is just a class that implements IDataStore. However MsSqlDataStore and MySqlDataStore will share common code. They will both inherit from the abstract class SqlDataStore which implements IDataStore.

    0 讨论(0)
  • 2020-12-24 04:37

    Basically, an interface defines a 'contract' (i.e. a set of operations/properties) that all implementers must provide. In this case the IAnimal interface requires the WhatAmI and WhatIsMyName properties. Abstract classes may provide certain functionality, yet will also leave some operations which must be implemented by their subclasses.

    In the case of your example, the Animal base class is able to provide the WhatIsMyName functionality since 'Name' is a property of all animals. However, it cannot provide the 'WhatAmI' property, since only specific subclasses know what 'type' they are.

    The problem with the sample code you posted, is that thet Animal class has knowledge of it's subclasses, which it should not have

    0 讨论(0)
  • 2020-12-24 04:38
    1. An interface is a contract. This is the place where you want to describe the functionalities you'll provide, without any implementation details

    2. An abstract class is a class whose purpose is to share implementation details between its sub-classes. Since it's here only for code sharing/factorisation purposes, it cannot be instantiated

    3. your actual class will inherit from your abstract class, and implement its class-specific functionalities while using the code shared in the abstract class if needed.

    0 讨论(0)
  • 2020-12-24 04:42

    Generally speaking:

    • An interfaces describe the methods an object will respond to. It is a contract the object commits to satisfy.

    • Abstract classes describes basic functionality and let specialized functionality to a subclass.

    So, basically you use an interface when you want that objects different in nature, respond to the same specific method.

    And you use an abstract class when you need to have specialized versions of some class.

    Let's say you want to create a system where any kind of object may be identified by an unique id, and you don't care the class they belong to.

    You may have:

    • Animals

    • Transport

    • Computer gadgets.

    • Whatever.

    Since they are unrelated topics, you may choose to implement and interface, let's say:

    public interface IIdentifiable 
    { 
    
          public long GetUniqueId();
    }
    

    And all the classes that want to satisfy this contract will implement that interface.

    public class IPod: IIdentifiable 
    {
          public long GetUniqueId() 
          {
               return this.serialNum + this.otherId;
          }
    }
    
    public class Cat: IIdentifiable 
    {
          public long GetUniqueId()
          { 
               return this.....
          }
    }
    

    Both, and IPod and a Cat, have very different natures, but they both may respond to the "GetUniqueId()" method, that will be used in the catalog system.

    Then it may be used like this:

        ...
    
        IIdentifiable ipod = new IPod(); 
        IIdentifiable gardfield = new Cat();
    
        store( ipod );
        store( gardfield );
    
    
        ....
        public void store( IIdentifiable object )  
        {
    
             long uniqueId = object.GetUniqueId();
            // save it to db or whatever.
        }
    

    On the other hand, you may have an abstract class defining all common behavior the object may have, and let the subclass define specialized versions.

      public abstract class Car 
      {
           // Common attributes between different cars
           private Tires[] tires; // 4 tires for most of them 
           private Wheel wheel; // 1 wheel for most of them.
    
            // this may be different depending on the car implementation.
           public abstract void move(); 
      }
    
    
      class ElectricCar: Car 
      {
          public void move()
          {
             startElectricEngine();
             connectBattery();
             deploySolarShields();
             trasnformEnertyToMovemetInWheels();
          }
      }
    
      class SteamCar: Car 
      {     
           public void move() 
           {
              fillWithWather();
              boilWater();
              waitForCorrectTemperature();
              keepWaiting();
              releasePreasure....
            }
       }
    

    Here, two kinds of cars, implements the "move" method in different ways, still they share common things in the base class.

    To make things more interesting, these two cars may implement also de IIdentifiable interface, but by doing so, they are just commiting to respond to the GetUniqueId method, and not by the nature of being cars. That's why the Car it self may not implement that interface.

    Of course, if the identification may be based on the common attributes the cars may have, the GetIdentifiableId may be implemented by the base class and the subclasses will inherit that method.

    // case 1 ... each subclass implements the interface

       public class ElectricCar: Car, IIdentifiable 
       {
           public void move()
           {
             .....
           }
           public long GetUniqueId() 
           { 
             ....
           }
       }
    
       public class SteamCar: Car, IIdentifiable 
       {
           public void move()
           {
             .....
           }
           public long GetUniqueId() 
           { 
             ....
           }
      }
    

    Case 2, the base class implements the interface and the subclass benefit from it.

       public abstract class Car: IIdentifiable 
       {
           // common attributes here
           ...
           ...
           ...
    
    
    
           public abstract void move();
           public long GetUniqueId()
           {
              // compute the tires, wheel, and any other attribute 
              // and generate an unique id here.
           }
       }
    
       public class ElectricCar: Car
       {
           public void move()
           {
             .....
           }
       }
    
       public class SteamCar: Car
       {
           public void move()
           {
             .....
           }
      }
    

    I hope this helps.

    0 讨论(0)
  • 2020-12-24 04:46

    The main difference between an interface and an abstract class is that in the interface you only define what should be the public methods and properties of the object that implements this interface. An abstract class provides some base implementation, but has some "gaps" - abstract methods that the inheritor needs to implement.

    I am not going to do your homework for you, but a hint: the Animal class should NOT contain anything specific for dogs and cats.

    0 讨论(0)
  • 2020-12-24 04:46

    Abstract Classes: Establish a base for derived classes they provide a contract for all derived classes. It enforces heirarchies

    Interfaces:

    An interface is not a class, its a definition of methods.

    A class can inheirt multiple interfaces but only one abstract class.

    I hope that helps

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