Problems with multiple inheritance and interface use

Asked

Viewed 257 times

2

I am creating a simple bank system (studying), there is a Account class with basic registration information, and a System class that manages all accounts. I intend to create a class ContaDiretor which should extend from Conta (as it is an account) and Sistema (as it must have access to class-unique methods/attributes Sistema).

package Conta;

import Banco.Cliente;
import Banco.Data;

public class Conta {

    public int numero;
    protected double saldo;
    public String extrato[] = new String [100];
    public Cliente titular = new Cliente();
    public Data DataDeAbertura = new Data();

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

    }

    public double getSaldo(){

        return saldo;
    }



    protected boolean podeSacar(double valor){

        if (saldo < valor)
            return false;
        else
            return true; 

    }

    public void sacar (double valor, Conta conta){
        if (podeSacar(valor)) {

            saldo -= valor;
            System.out.println("Novo Saldo: ");
            System.out.print(conta.getSaldo());
            System.out.println("");

        }    
        else 
            System.out.println("Saldo indisponível");

    }



    public void transferencia (Conta c2){

    }

    public void getExtrato () {

        for (int i = 0; i < extrato.length; i++) {
            if (extrato[i] == null){
                break;
            }
            else
                System.out.println(extrato[i]);

        }



    }

    public void setExtrato(String nome, String atividade, double valor) {

        String extrato = nome + " " + atividade + " " + Double.toString(valor);
        for (int i = 0; i < this.extrato.length; i++) {
            if (this.extrato[i] == null) {

                this.extrato[i] = extrato;
                break;
            }

        }


    }
    public void setExtrato(String nome, String atividade, double valor, String nome2) {

        String extrato = nome + " " + atividade + " " + Double.toString(valor) +" para "+ nome2;
        for (int i = 0; i < this.extrato.length; i++) {
            if (this.extrato[i] == null) {

                this.extrato[i] = extrato;
                break;
            }

        }


    }

    public boolean contaequals(Conta a){

        return (this.titular.login == a.titular.login);        
    }
}

    package Banco;

import Conta.Conta;

public class Sistema{

    public Conta contas[] = new Conta[100];
    public Conta contaPublic = new Conta();

    private String nomeBanco = "Banco do Brasil"; //O diretor deve ser o único capaz de alterar o nomeBanco
    private int totalContas = 0; //O diretor deve ser o único capaz de receber totalContas

    public String getNomeBanco() {
        return nomeBanco;
    }

    public void adicionaConta(Conta conta){

        this.contas[totalContas] = conta;
        totalContas++;


    }


    public Conta getConta(int pos) {
        return contas[pos];
    }

    public Conta[] getContaVetor() {//retorna o vetor inteiro
        return contas;
    }


}

I know very little of interface, I tried to create one, but found that all attributes of an interface are final (are not modifiable).

If I create in the interface the abstract methods as setNomeBanco and getTotalContas as ContaDiretor will change the attributes that only exist in Sistema?

I don’t want to leave you public (totalContas and nomeBanco) because I just want ContaDiretor can receive and change them respectively.

Like ContaDiretor will inherit the methods and attributes of the Account and System classes at the same time?

Below is the class draft ContaDiretor and interface SistemaInterface:

 package Conta;

import Banco.InterfaceSistema;

public class ContaDiretor extends Conta implements InterfaceSistema{
    public static String nomeDoBanco;

    public void setNomeDoBanco(String nome) {
        this.nomeDoBanco = nome;
        // TODO Auto-generated constructor stub
    }

    public String getNomeBanco() {

    }



}

    package Banco;

import Conta.Conta;

public interface InterfaceSistema {


    public String getNomeBanco();

    public void adicionaConta(Conta conta);

    public Conta getConta(int pos);

    public Conta[] getContaVetor();




}
  • 2

    Try with composition, maybe it will. I recommend the reading

  • Java does not have multiple inheritance. You can extend from just one class. Interfaces are contracts where the methods to be implemented are defined by the classes that will execute the behavior defined by the interface. More about interfaces.

  • ContaDiretor is a Conta which is managed by Sistema. It makes no sense to have system features. What is the problem statement? With this information will be easier to help you.

1 answer

5


There are several problems with this code, including conceptual ones. One of them begins by the name of things, a very important one is that it seems that there are actually objects that are Conta and objects that are ContaDiretor, this does not seem right, at least by the names and way of using. If this class Conta is abstract and can not have objects of it there I think it can make sense, not yet guarantee, I can only guarantee knowing the problem in detail, and then this interface seems to make less sense yet, although it may have and not be in the clear in the question.

That one contaequals makes less sense yet, not only by default name, but mostly because it’s probably wanting to overwrite the method equals() that every object has, it would be good to study this before trying to implant something like this.

There are methods that shouldn’t be there. There are people who like this, but extract is something separate from the account. Account is account, caring for an extract is something that can happen in various ways and change, and have alternatives, and may not be able to do in certain situations. Anyway, it’s not your responsibility to handle this. The guy Conta have to have the means to give information necessary to generate an extract but not to take care of it. Nor should the extract data be there.

In class Conta you have a list of accounts and you can add something there? This doesn’t make any sense, especially the way it was implemented. An account must have data of one account, if it were about a list of accounts the class should call Contas or even another more significant name, and then, of course, there should be no individual account data.

I do not like and many people say that it is quite wrong to use getters and setters in this way. It seems that they exist to follow cake recipe that someone (who probably did not know what he was saying) said should do so. One does not know well why is doing this and to know why (really, not superficially) is more important than knowing what to do.

The methods mix responsibilities and treats IO in a business class, this makes no sense. And even what these methods do are strange things.

Interestingly if it wasn’t OO I wouldn’t have to think about any of this stuff.

I know, it’s just an exercise, but it seems to be an OOP exercise, and OOP is just putting together an object in a way that makes sense. Object-oriented programming is not playing a lot of code by following a few rules, it is organizing the code in a way that solves a problem in the best way possible. What many people don’t understand is that OO is to understand the problem and move to the code so that it is easier to visualize everything as it really is and be easy to move in the future. If you don’t do it right, it’s better not to do it this way. You’re creating code complexity for zero benefit. Actually, there’s often harm. It is necessary to have a deep understanding of computing, of software engineering and to focus on the problem to be solved until you understand it properly, something that people rarely do, they "always" get it wrong, because the problem is not always as apparent as it really is, especially if you trust the user who doesn’t usually understand what I’m talking about. There’s an organizational problem that prevents software from being good if the developer doesn’t realize it. Even worse when the problem is artificial, then it will go wrong and the person will learn to do something crooked the first time and will make even more crooked the next. You do what you train, if you train the mistake that’s what you’ll always do.

What you call an attribute is actually called a field. I know you learned that way, and that’s what I’m saying, it’s common to teach wrong. And interfaces don’t have fields, or attributes like you called them (attributes even exist in it, but that’s not what you think it is, so for all intents and purposes consider that it doesn’t, it’s something less important and more academic to know that it has real attributes, will be useful one day when you want to go deeper but not now). That’s why training too much can be a problem, because you may be training error.

If I create in the interface the abstract methods as setNomeBanco() and getTotalContas() as ContaDiretor will change the attributes that only exist in Sistema?

It seems to me that this interface has to do with class Sistema and not ContaDiretor, Sounds like you’re trying to stick her in there anyway, even though you have no reason to. Not that I’m saying that the interface should exist, on the contrary, it doesn’t seem like it does, but it might just be because the question doesn’t make that clear. Only use something you can justify (properly) because you are creating it. In the question you do not seem to need. I don’t really know if I should have the class Sistema (maybe, just not so clear in this form). May need another class similar to that.

When an interface has Interface in the name already indicates that there is something very wrong there. Interfaces are contracts with the capabilities of an object to do something. Behold How and when to use Interface? and Principle of Liskov’s replacement.

Like ContaDiretor will inherit the methods and attributes of the Account and Sistema at the same time?

It won’t, it doesn’t make any sense to do this. ContaDiretor is not a Sistema, in fact should even be composed of a Sistema, unless wrong understanding that the question did not make clear.

A collateral error, which for an exercise is not serious, but it’s good to know the right one, is that monetary values cannot be of the type double.

Another side item is that if you have one if that inside there’s only one return true or false, should eliminate the if and make the boolean expression directly on return.

  • Thank you for answering, I’m reading today for the first time, this project is somewhat old. The solution I found was to create a package for accounts (I believe) and change some variables to protected. I didn’t even know what an interface was at the time, I finished this mini-bank with about 12 classes off the graphical part. I created a working interface for classes like Manager and Manager (which accessed different menus). I confess that a lot of the errors you pointed out I did not correct and nor did I realize they existed. I will reopen this project to make these changes.

Browser other questions tagged

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