Change super class value using subclass method

Asked

Viewed 163 times

1

The method sacar() does not work, does not change the value of the balance.

I make the deposit using super class method ContaBancaria direct, the sacar() is of class ContaPoupanca that extends the super class, but I say, super.getSaldo() and yet the value of the loot is not deducted.

If I use this.getSaldo() or super.getSaldo() the Eclipse shows that the reference is in the class ContaBancaria, but subtraction doesn’t happen when I run.

public class ContaBancaria {

    private double saldo;

    public double getSaldo() {
        return saldo;
    }
    public void setSaldo(double saldo) {
        this.saldo = saldo;
    }

    public void depositar(double valor) {
        this.saldo += valor;
    }

    @Override
    public String toString() {
        return "Saldo: " + saldo;
    }
}

public class ContaPoupanca extends ContaBancaria{

    private int diaRendimento;

    public int getDiaRendimento() {
        return diaRendimento;
    }
    public void setDiaRendimento(int diaRendimento) {
        this.diaRendimento = diaRendimento;
    }

    public void sacar(double valor) {
        if (valor < super.getSaldo()) {
            super.setSaldo(super.getSaldo() - valor);
            System.out.println("Saque realizado com sucesso!\nSaldo: " + super.getSaldo());
        } else {
            System.out.println("Saldo insuficiente.\nSaldo: " + super.getSaldo());
        }
    }

    public void calcularNovoSaldo(int dia) {
        if (dia >= 15) {
            System.out.println("Rendimento: " + (this.getSaldo() + 100));
        } else {
            System.out.println("Sem rendimento. Saldo: " + this.getSaldo());
        }   
    }   
}

public class Ex01 {

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);

        ContaBancaria conta = new ContaBancaria();
        ContaPoupanca poupanca = new ContaPoupanca();

        boolean sair = false;

        while (!sair) {
            System.out.println("1. Depositar");
            System.out.println("2. Sacar");
            System.out.println("3. Saldo em conta");
            System.out.print("0. Sair\nDigite a opção: ");
            int opcao = scan.nextInt();
            System.out.println();
            if (opcao == 1) {
                System.out.print("Digite o valor do depósito: ");
                conta.setSaldo(scan.nextDouble());
            } else if (opcao == 2) {
                System.out.print("Digite o valor do saque: ");
                double valor = scan.nextDouble();
                poupanca.sacar(valor);
            } else if (opcao == 3) {
                System.out.println(conta);              
            } else if (opcao == 0) {
                System.out.println("Saindo.");
                sair = true;                
            }
            System.out.println();
        }

        scan.close();
    }
  • It doesn’t work either. What I think is happening is that he is trying to mess with the Savings Account balance, but I’m saying in the code that is for him to subtract from the Account.

  • 1

    I tested here and it is working perfectly your code... I simplified your test to be fully java: public static void main(String[] args) {&#xA; ContaPoupanca c = new ContaPoupanca();&#xA; c.depositar(100);&#xA; c.sacar(10);&#xA; System.out.println(c);&#xA; } and the result is correct

1 answer

2


The problem is that you have created two different accounts:

ContaBancaria conta = new ContaBancaria();
ContaPoupanca poupanca = new ContaPoupanca();

Each of these variables is a different instance, and each has its own balance (which by default, starts with zero value, since you do not specify any).

Then you deposit into the variable conta, what makes her balance increase. But at the time of making the withdrawal, you try to do in the variable poupanca, whose balance is always zero, since at no time do you modify it (you changed the balance of the variable conta, but of poupanca nay).


I think you’re making a little mess.

The class ContaPoupanca is a subclass of ContaBancaria, then she inherits the methods getSaldo(), setSaldo() and depositar(). Both classes have these methods: ContaBancaria possesses because she defined them, and ContaPoupanca possesses because it inherited from ContaBancaria.

Do super.getSaldo() serves to call the method of the parent class (which the daughter class also possesses, via inheritance). It does not serve to call the method in another variable that has the same parent type.

And in this case, the daughter class (ContaPoupanca) does not override the method getSaldo(), then the super is redundant. You could write only getSaldo() (without the super), that Java checks if the method exists in the class, and if it does not exist, searches in the parent class. In the end, it will end up finding the method in ContaBancaria.

Anyway, a simple way to solve your problem would be to have only one account:

// crie apenas uma conta
ContaPoupanca conta = new ContaPoupanca();

boolean sair = false;
while (!sair) {
    ... aqui não muda
    if (opcao == 1) {
        ... 
    } else if (opcao == 2) {
        System.out.print("Digite o valor do saque: ");
        double valor = scan.nextDouble();
        conta.sacar(valor); // sacar da conta
    } else if (opcao == 3) {
       ....
}

As an addendum, it is not a good idea to have a method setSaldo(), as this allows you to change the balance of an account with any arbitrary value (every account should only have its balance changed via withdrawals and deposits).

An option to delete this - and keep your class model - is to change the saldo for protected (so subclasses can access it too):

public class ContaBancaria {
    protected double saldo;

    public double getSaldo() {
        return saldo;
    }

    public void depositar(double valor) {
        this.saldo += valor;
    }
}

And in the subclass you can use it directly:

public class ContaPoupanca extends ContaBancaria {
    public void sacar(double valor) {
        if (valor <= this.saldo) { // <-- repare no <=
            this.saldo -= valor;
            System.out.println("Saque realizado com sucesso!\nSaldo: " + this.saldo);
        } else {
            System.out.println("Saldo insuficiente.\nSaldo: " + this.saldo);
        }
    }

    public void calcularNovoSaldo(int dia) {
        if (dia >= 15) {
            System.out.println("Rendimento: " + (this.saldo + 100));
        } else {
            System.out.println("Sem rendimento. Saldo: " + this.saldo);
        }
    }
}

I also switched the < for <= in the if (valor <= this.saldo), to allow the person to withdraw all the money.

There are still other details to improve, such as checking if the nextDouble() actually returned a number (it casts an exception if a valid number is not entered), and notes that it is not necessary to close the System.in (see a more detailed discussion on this in this answer).


If you want a bank account to also have a connected savings account, that’s another story. It would be the case to change the modeling, probably using composition instead of inheritance. I’m not getting into this because it’s already outside the scope of the question.

Browser other questions tagged

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