Exemplos Práticos
💻 Exemplo 1: Classe Produto com Encapsulamento
class Produto {
#preco = 0;
#estoque = 0;
constructor(nome, preco, estoque) {
this.nome = nome; // Público
this.setPreco(preco);
this.setEstoque(estoque);
}
getPreco() {
return this.#preco;
}
setPreco(valor) {
if (typeof valor === 'number' && valor >= 0) {
this.#preco = valor;
}
}
getEstoque() {
return this.#estoque;
}
setEstoque(valor) {
if (Number.isInteger(valor) && valor >= 0) {
this.#estoque = valor;
}
}
vender(quantidade) {
if (quantidade <= this.#estoque) {
this.#estoque -= quantidade;
return true;
}
return false;
}
}
💻 Exemplo 2: Classe Usuário com Getters/Setters
class Usuario {
constructor(email, senha) {
this._email = email;
this._senha = senha;
this._ativo = true;
}
get email() {
return this._email;
}
set email(novoEmail) {
if (novoEmail.includes("@")) {
this._email = novoEmail;
}
}
get ativo() {
return this._ativo;
}
ativar() {
this._ativo = true;
}
desativar() {
this._ativo = false;
}
alterarSenha(senhaAntiga, senhaNova) {
if (senhaAntiga === this._senha && senhaNova.length >= 6) {
this._senha = senhaNova;
return true;
}
return false;
}
}
💻 Exemplo 3: Classe Carro com Métodos de Instância
class Carro {
#velocidade = 0;
#ligado = false;
constructor(marca, modelo) {
this.marca = marca;
this.modelo = modelo;
}
ligar() {
this.#ligado = true;
return "Carro ligado!";
}
desligar() {
this.#velocidade = 0;
this.#ligado = false;
return "Carro desligado!";
}
acelerar(valor) {
if (this.#ligado && valor > 0) {
this.#velocidade += valor;
return `Velocidade: ${this.#velocidade} km/h`;
}
return "Carro precisa estar ligado!";
}
frear(valor) {
if (this.#velocidade > 0) {
this.#velocidade = Math.max(0, this.#velocidade - valor);
return `Velocidade: ${this.#velocidade} km/h`;
}
return "Carro já está parado!";
}
getVelocidade() {
return this.#velocidade;
}
}