What is the relationship between encapsulation and polymorphism?

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

Since they were very late, I asked how they made a jump to inheritance suddenly, I asked if they had ever studied polymorphism and encapsulation, then he replied:

Isn't it all the same?

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

  • Polymorphism and encapsulation are the same thing?
  • are there relations between these two concepts, to the point of speaking"that they are the same thing"?
  • if they are not the same thing, could you give some explanations and if possible, an example of how they work?
Author: UzumakiArtanis, 2017-06-22

2 answers

It's not all the same.

College means very little. She is useful, but having a diploma does not guarantee anything. Most students learn to be great truco players in the schoolyard. In general people seek to learn fragments and think they know everything. Few are committed to the right understanding. Even fewer are those who have criticality to avoid going out talking about what they do not know. And when one learns, in general it is decoreba and does not even understand what you're talking about.

In general OOP is like teen sex, everyone says it does, but do even, few. And where it does, I don't know if it should. OOP really complicates the code a lot, so maybe it's better not to do oop right even, the problem is that you have to do not consciously and not by chance.

Most can't even define what oop is 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 abstraction as another component.

Including they can and are used in other paradigms jointly 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 think, getters and setters serve encapsulation, but it is not encapsulation itself, this is abstraction. Encapsulation is about holding together what is necessary to achieve the object's goal, so all that can be done with that object must be part of it, but must not be directly exposed unless necessary. In fact this is even a little more complicated, because it is common for us to want most operations with an object to be done outside of it, but this is another matter.

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

Encapsulating is not separating the program into parts.

Tragically the getters and setters are exemplified as encapsulation and as people don't quite understand the concept they think that's it. Interestingly, those who like good practices should know the good practice that says that they are not good, they just tend to be better than leaving everything public when there is no other way, unless they are not.

Polymorphism

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

There are some forms of polymorphism, but all of them, one way or another, are substitutes for one if. The more traditional polymorphism, the dynamic or subtype is just the choice of which method to perform based on the type of the object that has some relation, in general a indirection is made in the call of the method according to a table.

The parametric polymorphism is usually resolved 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 signature of the method, called overloading or ad-hoc , which is not what we are dealing with here, this is not what OOP is about.

Extra information

Has 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

Can have errors, do not know or compile, it's just to show the concepts, I made huge simplifications. Note that it does not have such a direct relationship between methods and fields. 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 put on GitHub for future reference .

 11
Author: Maniero, 2020-06-11 14:45:34

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

Polymorphism is a specialization. Choose the best algorithm for a particular class. An example of polymorphism is the "move" function. For chess and checker games, she will have a different behavior.

 0
Author: LucasDelboni, 2017-06-22 19:39:59