DEV Community

Cover image for Objetos Imutáveis
Antonio Serra
Antonio Serra

Posted on • Edited on

2 1 1 1 1

Objetos Imutáveis

Objetos imutáveis são objetos cujo estado não pode ser alterado após a sua criação. Isso significa que, uma vez que você defina os valores dos atributos de um objeto imutável, esses valores não podem ser modificados. Isso é alcançado tornando os atributos privados e fornecendo métodos apenas para leitura, sem métodos para alteração.

Aqui está um exemplo simples de uma classe de objeto imutável em Java:

public final class PessoaImutavel {
    private final String nome;
    private final int idade;

    public PessoaImutavel(String nome, int idade) {
        this.nome = nome;
        this.idade = idade;
    }

    public String getNome() {
        return nome;
    }

    public int getIdade() {
        return idade;
    }
}
Enter fullscreen mode Exit fullscreen mode

Neste exemplo, os atributos nome e idade são marcados como final e só podem ser definidos no construtor. Não há métodos para alterar esses valores depois que o objeto é criado.

Linkedin: https://www.linkedin.com/in/antonio-rodrigo-wanderley-serra/
GitHub: https://github.com/antoniorws

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay