Abstract Class X Interface

Asked

Viewed 32,712 times

49

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

  • Take a look at this post, http://www.guj.com.br/java/102664-quando-usar-a-classe-abstraction-e-a-interface It should help you ;)

  • In this post you have a detailed explanation: http://www.devmedia.com.br/interfaces-x-classes-abstraction/13337

6 answers

44


An abstract class can contain logic (code), while 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 is not abstract) or that implements the interface.

Example of abstract class:

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);
}
  • 3

    I usually use abstract class when some implemented method can be used in derived classes. Otherwise it is usually Interface.

  • @bigown - grateful for the edition. Unfortunately I don’t have keyboard :)

26

To complement Otavio’s response:

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

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

When thinking of using abstract classes and inheritance, remember the LSP (Liskov Substitution Principle). This principle says that if a class Derivada class-derived Base, then any code you use Base can also use a Derivada no surprising effects.

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

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

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

12

Complementing the staff response.

Abstract class

It is a type of class that can only be inherited and not instantiated. In a way, one can say 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 an object will be required to implement. It is important to remember that an interface never contains implementation, that is, in an interface you cannot define fields, because they are an implementation of an object attribute. The interface also does not allow constructors, because in a constructor we have the instructions used to initialize fields. In order to use an interface, we must create a class or structure and inherit from the interface. With this, it is mandatory to implement all interface methods.

Completion

An abstract class may contain complete or incomplete methods. An Interface may 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 cannot contain fields, constructors, or destructors. It can have 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 its methods, but the same is not required in the case of an abstract class. Abstract classes are faster than interfaces.

10

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

I don’t know any example of an abstract class in C#. In fact, they are quite rare in the . NET framework.

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

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

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

  • 4

    André, correct. They are not so rare. Most providers have deployments in abstract classes. (Role, Membership, User and etc)

  • As Cleiton said the abstract classes are much used, I believe even more than the Interfaces. But we usually already consume concrete classes that we inherit from them. Database classes and controls are some examples of these classes. We usually use the concrete implementation. When trying to make a library it is that we end up arriving at them more often.

  • As I said, I do not know. Feel free to edit my answer and increase it if you want. After all, they are examples, that can never be too many. Thank you.

6

To understand the difference between abstract classes and Interfaces I believe it will be necessary to resort to history in order to elucidate how things occurred.

Even though it already existed in the early days of the creation of object orientation, such as Smalltalk and others, interfaces were created on Windows to be able to support more simply , in 1992, the architecture model of Microsoft called COM for Interprocess Communication (IPC) what DDE and OLE are like.

COM, COM+ and DCOM are evolutions of DDE and OLE. Corba is COM’s Competitor.

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

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

Interfaces also play a role similar 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 : Abstract concepts for future implementation.

That is why it is difficult to understand the differences and the question could also be formulated in this way : Why have they made available 2 ways to abstract implementations ? The answer Srs. is in the history of Windows itself, Interfaces were implemented in the Operating System to serve COM.

But since interfaces also serve the purpose of abstracting concepts, why not use it ? Then they began to use it with these objectives, but they did not necessarily do IPC (interprocess comunication) and COM and hence the resemblance with the abstract classes.

The lack of knowledge of history makes it possible to justify the use of one to the detriment of 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 abstract classes have even more resources than an interface, such as the possibility of creating methods, fields and states, which an interface cannot. Then it would be the case to opt for Abstract Classes instead of interfaces. It is also not the case to compare in terms of performance, because the concrete classes of both have the same form of access to 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 cannot. This is the only conceptual distinction I see between them, this difference, by the way, very few times used in everyday life and in the architecture of nonbasic software.

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

These common objectives are :

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

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

Therefore, having in mind the objective of abstracting concepts, it makes use of either one or the other, with slight advantage in using abstract classes for having greater resources.

Sources : https://en.wikipedia.org/wiki/Component_Object_Model https://en.wikipedia.org/wiki/Distributed_Component_Object_Model https://en.wikipedia.org/wiki/Common_Object_Request_Broker_Architecture https://en.wikipedia.org/wiki/Globally_unique_identifier

-1

Abstract Class

It is a class that serves as a model for other classes, but should not be instantiated itself. For example, the class "vehicle". It may contain several characteristics of a car, ship or plane, but it will not become something concrete (instantiated). The class "car", which contains the attributes and methods of the class "vehicle", will be instantiated.

Interface

The interface can be understood as a special type of abstract class, where it contains only special attributes (Static and final) and all its methods are implicitly Abstract and public and have no body. This implies that interfaces cannot be instantiated and therefore cannot display constructors; their methods will also only have the signature. Something important to say is that the interface does not need to be used in inheritance situations. For example, suppose the classes A, B and C are heirs of the abstract class Z. And we want to assign only the classes B and C given behavior. If it were done by the abstract class Z all would inherit, then we solved this by creating an interface and relating it only to B and C.

Just remembering that all abstract methods, whether of the abstract class or of the interface, will have to be implemented by the heirs classes.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.