What is the relationship between encapsulation and polymorphism?

Asked

Viewed 1,800 times

10

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

As they were too late, I asked how they suddenly jumped to inheritance, I asked if they had ever studied polymorphism and encapsulation, so he replied:

It’s not all the same?

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

  • Polymorphism and encapsulation are the same thing?
  • There are relations between these two concepts, to the point of speaking "that are the same thing"?
  • If they are not the same thing, they could give some explanations and if possible, an example of how they work?

2 answers

12


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 truco players in the schoolyard. In general people try to learn fragments and think they know everything. Few are committed to the right understanding. Even fewer are those who are critical to avoid talking about what they do not know. And when one learns, in general it is decorate and you don’t even understand what you’re talking about.

In general OOP is like teenage sex, everyone says they do, but they do, very few. And where it does, I don’t know if I should. OOP actually complicates the code a lot, so maybe it’s better not to do OOP right, the problem is you need to do it with awareness and not by chance.

Most can’t even define what OOP is and each 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 place abstraction as another component.

Even they can and are used in other paradigms jointly or separately. It is not something exclusive to OOP.

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

Encapsulation

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

Contrary to what many think, getters and setters serve the encapsulation, but it is not encapsulation in itself, that is abstraction. Encapsulation is about keeping together what is necessary to achieve the object’s goal, so everything that can be done with that object must be part of it, but must not be exposed directly, unless necessary. Actually this is even a little more complicated, because it’s common that we want most operations with an object to be done outside of it, but that’s another matter.

Making something private is a very used mechanism, but strictly speaking it’s not encapsulation itself.

Encapsulating is not separating the program into parts.

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

Polymorphism

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

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

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

Extra information

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

Example

I don’t know if it compiles, it’s just to show the concepts, I made huge simplifications. Note that there is no such direct relationship between methods and fields. I did not fall into encapsulation. 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 in the Github for future reference.

  • Where’s the rest of the answer?

  • 1

    @Jeffersonquesado calm, we get there :)

1

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

Polymorphism is a specialization. Choosing the best algorithm for a given class. An example of polymorphism is the "move" function. For chess games and lady, it will have a different behavior.

Browser other questions tagged

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