What is the relationship between encapsulation and polymorphism?

9

A few days ago, I was talking to a friend about Java, and asked what part of the subject they were studying. So he replied that they were starting their studies on inheritance.

As they were long overdue, I asked how they suddenly jumped to inheritance, asked if they had already studied polymorphism and encapsulation, so he replied:

  

Is not it all the same?

At the moment I did not think of anything, after all I'm learning and he already has college. But analyzing better and assuming that two things should not be the same, even by different names,

  • Polymorphism and encapsulation are the same thing?
  • There are relations between these two concepts, to the point of saying "that they are the same thing"?
  • If they are not the same, could you give some explanations and if possible, an example of how they work?
asked by anonymous 22.06.2017 / 19:26

2 answers

10

It's not all the same.

College means very little. It is useful, but having a degree does not guarantee anything. Most students learn to be great trick players on the schoolyard. People often try to learn fragments and think they know everything. Few are committed to the right understanding. Even fewer are those who have criticality to avoid talking about what they do not know. And when the person learns, he / she is usually decoreba and does not understand what he is talking about.

In general OOP is like teenage sex, everyone says it does, but it does, very few.

Most can not even define OOP and every mechanism commonly used in this paradigm. Not to mention that there are different schools that define the term.

These two mechanisms, along with inheritance, are the basis of object orientation, although some disagree. They have different names because they are very different.

Some definitions put the abstraction as another component.

Even they can and are used in other paradigms together or separately. It's not something unique to OOP.

There is no relationship between them, they are completely orthogonal .

Encapsulation

Encapsulation could even be confused with abstraction, even though it is different. It's about hiding the implementation details.

Contrary to what many people think, getters and setters serve the encapsulation, but this is not encapsulation itself. Encapsulation is about keeping public only what is strictly necessary to achieve the object's goal, so anything that can be done with that object should be part of it, but it should not be exposed directly unless it is necessary. In fact this is even more complicated because it is common for us to want most operations with an object to be made out of it, but that is another matter.

Making something private is a much-used mechanism, but strictly speaking it is not the encapsulation itself.

Encapsulating is not separating the program into parts.

Tragically getters and setters are exemplified with encapsulation and as people do not quite understand the concept they think this is it. Curiously, those who like good practices should know good practice that says they are not good, they just tend to be better than leaving everything public when it has no other way, except when they are not .

Polymorphism

Polymorphism is about choosing the best algorithm for a given need.

There are some forms of polymorphism, but all, in one way or another, are substitutes for a if . The most traditional, dynamic or subtype polymorphism is just the choice of which method to execute based on the type of the object that has some relation, usually a #

The parametric polymorphism is usually solved at compile time according to the type of data used and some restriction . It is still possible to have a dynamic or static polymorphism, based on the method signature , called overloading or ad-hoc , which is not what we're dealing with here, is not it which OOP treats.

Additional information

There are a lot of questions on the subject right here in SOpt, just search. If you find something that has not been asked, you can ask a new question.

Example

It can have errors, do not know or compile, just to show the concepts, I made huge simplifications. Note that there is no such a direct relationship between methods and attributes. I did not fall into the encapsulation illusion . Java encourages polymorphism by making all methods virtual by default. See:

public abstract class Conta {
    private string documento; //todos aqui estão encapsulados
    private string titular;
    private BigDecimal saldo;
    private BigDecimal limite;
    private Date ultimaTroca;
    public Conta(string documento, string nome, BigDecimal saldo, BigDecimal limite) {
        if (!validaDocumento(documento)) {
            throw DocumentoInvalaidoException();
        }
        this.documento = documento
        this.nome = nome;
        this.saldo = saldo;
        this.limite = limite;
        ultimaTroca = new Date();
    }
    private bool trocaEstaDisponivel() { //encapsula a lógica de verificação, não interessa externamente
        return new Date().getTime() - ultimaTroca.getTime() < 1000 * 60 * 60 * 24 * 30 * 6;
    }
    private bool PodeSacar(BigDecimal saque) {
        return saldo + limite - saque >= 0;
    }
    protected abstract bool ValidaDocumento(string documento);  //encapsulado só entre a hierarquia, haverá polimorfismo
    public abstract bool CadastroValido(); //é polimorfico, só o descendente terá implementação
    public bool TrocaNome(string nome) { //público é o que pode fazer publicamente, o resto é detalhe interno
        if (trocaEstaDisponivel()) {
            this.nome = nome;
            return true;
        }
        return false;
    }
    public void Deposita(BigDecimal deposito) {
        saldo += deposito;
    }
    public bool Saca(BigDecimal saque) {
        if (PodeSacar(saque)) {
            saldo -= saque;
            return true;
        }
        return false;
    }
}

public class ContaJuridica : Conta {
    public ContaJuridica(string documento, string nome, BigDecimal saldo, BigDecimal limite) {
        Conta(documento, nome, saldo, limite);
    }
    @Override protected ValidaDocumento(string documento) {
        return true; //só para facilitar, aqui verificaria o CNPJ
    }
    @Override public CadastroValido() {
        return true; //aqui iria buscar na receita se o cadastro está ativou ou fazer outra coisa
    }
}

//o mesmo poderia ser feito para pessoa fisica

public class main() {
    public static void main (String[] args) {
        ContaJuridica conta = new ContaJuridica("01456789000159", "João da Silva", 100, 50);
        conta.Deposita(20);
        if (!conta.trocaNome("José da Silva)) System.out.println("Não pode ficar trocando nome toda hora");
        if (!conta.Saca(200)) System.out.println("Tá achando que o saco não tem fundo?");
        testarConta(conta.CadastroValido());
    }
    public void TestaConta(Conta conta) { //note que recebe uma Conta e não ContaJuridica, então o uso será polimorfico
        if (!conta.CadastroValido()) System.out.println("Sua conta precisa ser regularizada"); //chama método de ContaJuridica
    }
}

I placed GitHub for future reference .

    
22.06.2017 / 19:32
0

Encapsulate is to separate the program into parts, leaving it as separate as possible. This is to protect the manipulated data within the class.

Polymorphism is a specialization. Choose the best algorithm for a given class. An example of polymorphism is the "move" function. For chess and lady games, it will behave differently.

    
22.06.2017 / 21:39