What is the importance of using java interfaces or c#?

Asked

Viewed 882 times

4

I know how to implement and use interfaces, but I can’t understand what the real reason for them is in c# or java, since once you extend your class to an interface you need to implement all the interface methods.

2 answers

5

Basically, an interface is a contract, usually established for use between two distinct components, such as a system and a library, for example, or to reduce restrictions on the use of objects.

There are several uses. One of the most interesting is that of IEnumerable<T> in C#. The implementation of an enumeration may not be an object, but a generating function. Several objects implement IEnumerable<T>, as List<T>, arrays, Collection<T>, Queue<T>, Stack<T> and any function whose return is based on yield return, that accumulates multiple returns of objects that result in an enumeration by the calling method. This is a case of restriction reduction: when I declare:

IEnumerable<Objeto> lista;

I can assign to him any of the objects already cited:

lista = new List<Objeto>();
lista = new Collection<Objeto>();
lista = new Queue<Objeto>();
lista = new Stack<Objeto>();
lista = new Objeto[10];
lista = MinhaFuncaoComYieldReturn();

public static IEnumerable<Objeto> MinhaFuncaoComYieldReturn()
{
    for (var i = 0; i <= 10; i++)
        yield return new Objeto();
}

In addition, Java and C# are two languages that do not support multiple inheritance. Interfaces are a good way to ensure that a class is a composite of several different implementations.

An emblematic case of this is the class SortedDictionary<TKey, TValue>, also of the C#:

public class SortedDictionary<TKey, TValue> : IDictionary<TKey, TValue>, 
ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, 
IEnumerable, IDictionary, ICollection, IReadOnlyDictionary<TKey, TValue>, 
IReadOnlyCollection<KeyValuePair<TKey, TValue>>

It needs to be a dictionary, an enumeration, a collection, support sorting and still have read-only methods. This ensures a large amount of uses of the same data structure.

Java works the same way.

Finally, it is also worth talking about the exchange of components. Suppose for example that we have a class implemented in a library that for some reason we no longer want to use it:

public class ClasseDaBibliotecaASerRetirada 
{
    public void Metodo1(int i, int j) { ... };
    public int Metodo2() { ... };
    public int[] Metodo3(params int[] parametros) { ... };
}

We can extract the interface from it:

public interface IClasseDaBibliotecaASerRetirada 
{
    void Metodo1(int i, int j) { ... };
    int Metodo2() { ... };
    int[] Metodo3(params int[] parametros) { ... };
}

And implement another class, without modifying much of the code dependent on that class:

public class MinhaNovaClasse : IClasseDaBibliotecaASerRetirada 
{
    public void Metodo1(int i, int j) { ... };
    public int Metodo2() { ... };
    public int[] Metodo3(params int[] parametros) { ... };
}

4


The concept of developing interface-oriented code comes from the need to organize classes in a more cohesive way, with low coupling and well-encapsulated functionalities (foundations of Object Orientation).

Programming facing the interface requires abstracting the idea of implementation. I will try to summarize in a very simplistic way:

public class Empresa {

    public void efetuaPagamento(CNPJ cnpj, double valor){
        String cnpj = cnpj.getNumero();
        ...
    }

    public void efetuaPagamento(CPF cpf, double valor){
        String cnpj = cpf.getNumero();
        ...
    }

}

The Enterprise class is coupled with CPNJ and CPF. For each new document type you will need to copy the method. To prevent this, we can create an interface.

public interface Documento {

    public String getNumero();
}

And then the classes can implement them.

public class CNPJ implements Documento {

    public String getNumero(){
        //implementação
    }

    public void validaCNPJ(String cnpj){
        //implementação 
    }
}

public class CPF implements Documento {

    public String getNumero(){
        //implementação
    }

    public void validaCPF(String cpf){
        //implementação 
    }
}

Thus simplifying the Company class

public class Empresa {

    public void efetuaPagamento(Documento documento, double valor){
        String documento = documento.getNumero();
        ...
        }
}

Don’t get too attached to the content of the examples, the point is to understand that any change in the implementation will be done in a single point (CNPJ or CPF classes). The Company class is uncoupling, All she cares about is getting the document number, regardless of the document type. In addition to any new document, it will be enough to create a class and implement the Document, which will not affect the Company class at all.

  • I did not know that an interface could receive a class that implements the same, now I will be able to program more optimally, thanks.

  • @Fells, this way the code is cleaner and organized. I always had the question of how to use interfaces. I will go deeper into this subject because I want to use interfaces in the next projects I develop.

  • @Diegofarias In my opinion, the learning curve of Object Orientation is a little long. I myself took a long time to understand the concept in practice. You even understand when you read an article or see examples but the absorption only comes after you begin to realize the need to improve the quality of the code on a daily basis. This Caelum booklet exemplifies it in a very didactic way - https://www.caelum.com.br/apostila-java-orientacao-objetos/heranca-reescrit-e-polymorphism/

Browser other questions tagged

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