Correct use of Override and constructor

Asked

Viewed 691 times

2

I was asked to create a current account class that had an attribute representing the fee charged for each transaction of two attributes of the superclass (credit/debit).

And have been asked to subscribe to the credit and debit methods to discount the fee amount for each successful transaction.

I made the code that way:

public class ContaCorrente extends Conta {

    protected float taxa;

    public ContaCorrente(float saldoconta) {
        super(saldoconta);
    }   

    public void atualiza(float taxa){
        this.saldoconta = this.saldoconta - taxa;
    }

    @Override
    public void mostracredito(float valor) {
        // TODO Auto-generated method stub
        super.mostracredito(valor);
        this.saldoconta = this.saldoconta - this.taxa;
        System.out.println("Saldo da conta com desconto da taxa"+ this.saldoconta);
    }

    @Override
    public void mostradebito(float valor) {
        // TODO Auto-generated method stub
        super.mostradebito(valor);
        this.saldoconta = this.saldoconta - this.taxa;
    }   
}

So is that right? Or should I change something else? For all classes, the constructor was asked, that’s what complicated me.

This is the class Conta:

public class Conta {
    //ATRIBUTOS
    protected float saldoconta;

    //CONSTRUTOR
    public Conta(float saldoconta) {

        this.saldoconta = saldoconta;
    }

    //METODOS PUBLICOS
    public void mostrasaldo(){
        System.out.println("O saldo na conta é :" +this.getSaldoconta());
    }
    public void mostracredito(float valor){
        this.saldoconta = this.saldoconta + valor;
    }
    public void mostradebito(float valor){
        this.saldoconta = this.saldoconta - valor; 
    }
}
  • 4

    I don’t quite understand. What’s your question?

  • 1

    Let me get this straight, you did it, and you just want to know if you’re right? I don’t think it’s cool that kind of question, you want us to analyze your code, if you were in trouble all right but analyzing something you did is kind of tense.

  • I think I’m missing on how to put the discount method in the balance .

  • What do you mean: colocar o metodo de desconto no saldo?

  • I want to know if @Override is the way it uses . why in class the teacher did not pass super classes with constructor . so I got a little lost in it

  • It was requested that the debit and credit be made the discount ( using the rate attribute ) but I doubt if the code is correct .

  • @Felipelamarao The code does what is requested in the exercise?

  • @Felipelamarao The answer solved your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful for you. You can also vote on any question or answer you find useful on the entire site (when you have 15 points).

Show 3 more comments

2 answers

5

If I understood correctly, if the statement is correct, except for the fact that use float for monetary value that is a conceptual error that will calculate wrong values, but that doesn’t get in the way of an exercise, and that you can only subscribe to (using the posted terminology that I think was wrong) a method if it is an event (observer standard), you can override the method, it seems all right. Maybe the super should be called after calculating the balance, but I have no way of knowing if it is the desired, I’m just speculating.

The @Override that is correct.

Note that the constructor does not need it because in the background it is static, nor could it be different since the instance does not exist yet, it is he who will create it. Being static, there is no polymorphism and does not have to overwrite.

4

First, the correct term is aboutscrever, and not subscrever.

You have a method mostracredito and a mostradebito. These methods in the subclass not only show credit or debit, but they also change it, and therefore they don’t do what the method name says they do. Already in the superclass, these methods show nothing, although this is what the name indicates.

Therefore, its implementation is not adequate, because the name of a method should start what it does.

In addition, in a current account, the transactions made available must be for making a credit or a debit, and not for displaying a credit or a debit. The behavior of showing in this case is an intruder, it is not part of what the method should do. So much so that you were asked to overwrite the credit and debit methods to discount the rate value for each successful transaction, and that doesn’t mean showing anything.

And also, respect it the Java nomenclature rules, even more that this is an exercise in which you will be evaluated by a teacher.

And if you’re in a class called Conta, and you have an attribute called saldo, this can only be the account balance. Therefore, call the attribute saldoconta is redundant, saldo is sufficient. The same can be said of the method getSaldoconta - call it getSaldo is enough.

The fact that you leave the attribute as protected gives the subclasses the power to alter it however they want without the superclass supervising or interfering with anything. However, with this power also comes a responsibility: the subclasses have the responsibility to manage this attribute properly. However, if the superclass already provides methods to credit and debit amounts on the balance, then the superclass has already taken the responsibility to control this balance, so this is not something that should be passed on to the subclasses, who when accessing the balance directly, would then be violating the rules laid down in the superclass methods to manipulate the balance. This concludes that the balance attribute should be private.

We could take into account the point raised in Maniero’s response, the ideal type for the balance would be the BigDecimal.

In your subclass ContaCorrente, the method atualiza takes a rate as a parameter, but the class itself already has a rate as an attribute. Since this method does not use the parameter value to update the attribute, there are two different rates here. This is a modeling error in your class. In fact, the way your subclass is modeled, the rate that is in the attribute will always be zero.

The name atualiza is a very vague and generic name for an operation. The name taxar() is more precise. Moreover, if it is the responsibility of the subclass ContaCorrente discount the fee value for each successful transaction held in the account and it is the class that makes available what operations are to be carried out in that account, so it makes no sense for other classes to leave discounting the fee on their ownpleasure, for that is a responsibility that has already been taken entirely by the class ContaCorrente. Therefore, it probably does not make sense that the method taxar() be public, and therefore it is better for it to be private.

I’d make your superclass like this:

public class Conta {

    private BigDecimal saldo;

    public Conta(BigDecimal saldo) {
        if (saldo == null) throw new IllegalArgumentException();
        this.saldo = saldo;
    }

    public void mostrarSaldo() {
        System.out.println("O saldo na conta é: " + this.getSaldo().toPlainString());
    }

    public BigDecimal getSaldo() {
        return saldo;
    }

    public void creditar(BigDecimal valor) {
        if (valor == null) throw new IllegalArgumentException();
        this.saldo = saldo.add(valor);
    }

    public void debitar(BigDecimal valor) {
        if (valor == null) throw new IllegalArgumentException();
        this.saldo = saldo.subtract(valor);
    }
}

Your subclass would look like this:

public class ContaCorrente extends Conta {

    private BigDecimal taxa;

    public ContaCorrente(BigDecimal saldo, BigDecimal taxa) {
        super(saldo);
        if (taxa == null) throw new IllegalArgumentException();
        this.taxa = taxa;
    }

    public BigDecimal getTaxa() {
        return taxa;
    }

    public void setTaxa(BigDecimal taxa) {
        if (taxa == null) throw new IllegalArgumentException();
        this.taxa = taxa;
    }

    private void taxar() {
        super.debitar(taxa);
    }

    @Override
    public void creditar(BigDecimal valor) {
        super.creditar(valor);
        taxar();
    }

    @Override
    public void debitar(BigDecimal valor) {
        super.debitar(valor);
        taxar();
    }
}

Ah, note that the methods never accept balance, fee or amounts to credit or debit that are void. Rejecting null values is generally good programming practice (but it is not something that can always be applied).

Some rules on superscripts of methods:

  • In general, any method may be superscripted, except those:

    (a) are static, or

    (b) have the modifier final, or

    (c) are private or

    (d) are in a class final.

  • The annotation @Override may be added to methods that are superscripted from superclass methods. Its purpose is to force a build error if the method in question is not a superscript. In particular, this is useful for the compiler to complain when the superclass undergoes a change that will break the subclass, which is much better than the compiler quietly accepting a code where the subclasses are broken.

  • The ideal is that all methods that were superscripted had use of the @Override obligatory. However, its use is optional because of backward compatibility with versions of Java 1.4 and earlier that did not have this annotation.

  • When the superclass method is called with an instance of the subclass, and that subclass overrides the method, the invoked method will be the superscript in the subclass, not the superclass base method.

  • A subclass can access the methods it overrides from the superclass when using the reference super. For example to invoke the method x() of the superclass, having been superscripted in the subclass, should be used super.x().

  • Note that only the subclass can access the original superclass methods it overwritten. They cannot be accessed directly by other classes that are trying to use them by a reference to the subclass.

  • From Java 8, interfaces can have concrete methods with the modifier default. If a class X inherit two or more concrete implementations of the same method abc, either through the superclass or through interfaces (for example, interfaces Y and Z), she can access them through the syntax Y.super.x() or Z.super.x().

  • If a subclass defines a method with the same name as a superclass private method, this is not a superscript. It will only be a different method with the same name. The use of the annotation @Override in this case it will be a build error.

Some rules about constructors with subclasses:

  • In order for the subclass constructor to invoke the superclass constructor, there must be a call super(...) at the very beginning of the subclass builder.

  • The parameters of this call super(...) are the parameters of the superclass builder.

  • If the superclass has a constructor without parameters (even if it is the implicit constructor added by the compiler when no constructor is declared), then this is the constructor invoked if you do not have a call super(...) at the beginning of the subclass constructor. In this case, the compiler will place an implicit call to super(); there.

  • It is possible that a constructor invokes another constructor of the same class when using a call of type this(...) instead of super(...) at the beginning of the constructor. Again, the parameters of this call are the parameters of the constructor in question.

  • If the superclass does not have a constructor without parameters, then the constructor of the subclass will be required to invoke one of the constructors of the superclass with the super(...) or another constructor of the same class with the this(...).

  • Beware of builders of the same class calling the this(...) cyclically. If the builder To calls the builder B and the builder B calls the builder To, you will get a StackOverflowError if you attempt to instantiate that class.

  • Manufacturers may have any kind of visibility, including private.

  • It is not possible to override builders. In the superscript of a method, when the superclass method is invoked with an instance of the subclass, the invoked method is that of the subclass. In the constructor, you always invoke the subclass name with the new. As Maniero said in his reply, the instance does not exist yet in this case for the selection of some implementation. In the case of constructors, instead of superscript, we have chaining, since all subclass constructor should always call the superclass constructor.

  • Thank you very much friend !! really . I am still learning ,but I will continue studying a lot to improve more and more

  • @Felipelamarao If this answer has solved your problem, click the one next to the beginning of it to mark this answer as accepted and your question as solved. If you think the mustache answer is better, mark his. If this has not completely clarified your doubt, post some comments and we will clarify. Anyway, it is always a pleasure to help.

Browser other questions tagged

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