Abstract Class X Interface

41

What is the difference between an abstract class and an interface? I do not understand when I should use one or the other.

    
asked by anonymous 31.01.2014 / 19:08

5 answers

31

An abstract class can contain logic (code), whereas an interface can only specify which methods or properties (in the case of .NET) a class that implements the interface must define. However neither can be used to construct an object, so it is necessary to define a class that derives from the abstract (but that is not abstract) or implement the interface.

Abstract class example:

abstract class MaquinaDeLavar
{
   public MaquinaDeLavar()
   {
      // Codigo para iniciar o objeto.
   }

   abstract public void Lavar();
   abstract public void Enxaguar(int tamanhoCarga);
   abstract public long Secar(int velocidade);
}
    
31.01.2014 / 19:28
17

To complement Otavio's response:

Warning: inheritance (through abstract classes) should not be abused! Some people tend to abuse abstract classes with one goal in mind: reuse code , which would otherwise be repeated in concrete classes.

This is wrong! Inheritance must be used in one and only case: when there is a relationship it is a type of between the concrete and abstract classes. For example, "a cat is an animal type" or "an apartment is a type of house."

When thinking about using abstract classes and inheritance, remember the Liskov Substitution Principle (LSP). This principle says that if a Derivada class is derived from the Base class, then any code that uses Base can also use an instance of Derivada without surprising effects.

For example, at first glance, it may seem natural that Quadrado inherits from Rectângulo . The square is a type of rectangle, where the width is always equal to height.

In order to maintain this property, you can implement the Quadrado class like this:

public class Quadrado : Rectangulo
{    
    //propriedade herdada de rectangulo
    public override int Largura
    {
        get { return base.largura; }
        set 
        { 
            base.largura = value;
            base.altura = value;
        }
    }
}

Now imagine the following code:

public void Metodo(Rectangulo rect) {
  rect.Altura = 10;
  rect.Largura = 20;
  Console.WriteLine(rect.Altura);
}

This code expects to print 10 because it changed the height of the rectangle to 10. But if it is replaced by a square then it will print 20 !! This is an unexpected effect! So, although in the real world the square is a type of rectangle, it violates the LSP principle and there should be no inheritance relationship between the two.

Source: Liskov Substitution Principle

    
01.02.2014 / 10:08
9

An abstract class, in C #, is a class that defines basic behavior, but not self-sufficient. Because it is not enough, you need to create a class that inherits from it in order to use it.

I do not know any examples of an abstract class in C #. In fact, they are very rare in the .NET framework.

An interface does not define behavior. An interface is like a protocol. It defines to which actions a class that implements it should respond, but does not say how.

Common interface examples are IEnumerable (which says that a class should be enumerable) and INotifyPropertyChanged (which says that a class should send a notification when its properties are changed).

Note that in C #, it is convention to start interface names with a I uppercase.

    
31.01.2014 / 19:20
6

To understand the difference between abstract classes and Interfaces, I think it will be necessary to go through the story in order to elucidate how things happened.

Even though it existed in the early days of creating object orientation, such as smalltalk and others, the interfaces were created in Windows to support in a simpler way, in 1992, the Microsoft architecture model called COM for Interprocess Communication ) such as DDE and OLE.

COM, COM +, and DCOM are DDE and OLE evolutions. Corba is a COM competitor.

COM implements ABI, where an interface of an external application has a contract or interface for a call to be used by other applications. This contract acts as a signature containing the arguments, types, and result of the function, in addition to the GUID.

As the abstract classes did not have and were not appropriate because they were not made for this, for example an abstract class does not have a GUID that is the unique identifier of an interface, which is a requirement to work with COM. Then the interfaces fell like a glove to implement COM.

However Interfaces also play a similar role to Abstract Classes. When we look at Interfaces from the point of view of Object Orientation, we conclude that in generic terms they do exactly the same thing: Abstracting concepts for future implementation.

So it is difficult to understand the differences and the question could also be formulated in this way: Why did you provide 2 ways to abstract implementations? The answer is in the history of Windows itself, Interfaces have been implemented in the Operating System to serve the COM

But since interfaces also serve the purpose of abstracting concepts, why not use it? So they started using it with those goals, but they did not necessarily do IPC (interprocess communication) and COM and hence the resemblance to abstract classes.

The ignorance of history causes justification to use one over the other, and the mass use of one does not denigrate the use of another. Now if we compare the two from the OO point of view, we see that the abstract classes have even more features than an interface, such as the possibility of creating methods, fields and states, which an interface can not. So it would be the case that we opted for Abstract Classes instead of interfaces. It is not the case also to compare in terms of performance, since the concrete classes of both have the same form of access to the methods, via VMT (virtual methods table).

Other than the fact that the class that implements interface can have multiple inheritance of Interfaces, and a class that implements the abstract class can not. This is the only conceptual distinction I see between them, a difference, by the way, very rarely used in day-to-day and non-core software architecture.

Concluding: There are no conceptual differences in the objectives to be achieved by both the use of interfaces and the use of abstract classes, when we are NOT talking about IPC and COM.

These common goals are:

Providing cohesion, low coupling, independence of implementations for different situations, abstraction of concepts.

The differences are due to syntax, declarations, usage forms imposed by the compiler, memory release and whether it will work with COM or not.

So with the goal of abstract concepts in mind, either use one or the other, with a slight advantage in using abstract classes because they have more resources.

Sources: link link link link

    
08.11.2015 / 14:24
6

Complementing staff response.

Abstract Class

It is a type of class that can only be inherited and not instantiated. In a way, it can be said that this type of class is a conceptual class that can define functionalities so that its subclasses can implement them. The set of methods in the abstract class is mandatory, as is the implementation in its subclasses. In an abstract class, the declared methods can be abstract or not, and their implementations must be mandatory in the subclass.

Interface

Defines the operations that an object will be required to implement. It is important to remember that an interface never contains implementation, that is, in an interface can not define fields, since they are an implementation of an object attribute. The interface also does not allow constructors, since in a constructor we have the instructions used to initialize fields. To be able to use an interface, we must create a class or structure and inherit from the interface. With this, it is mandatory to implement all methods of the interface.

Conclusion

An abstract class can contain complete or incomplete methods. An interface can contain only the signature of a method, but no body or implementation. Therefore, in an abstract class, one can implement methods, but in an interface, no. An abstract class can contain fields, constructors, or destructors and apply properties. An interface can not contain fields, constructors, or destructors. You can own only the signature property, but not the implementation. An abstract class does not support multiple inheritance. Thus, a class can implement multiple interfaces, but only inherit from an abstract class. A class that implements an interface must implement all of its methods, but the same is not required in the case of an abstract class. Abstract classes are faster than interfaces.

    
18.01.2016 / 20:48