简体   繁体   English

我将如何实现接口?

[英]How would I implement the interfaces?

在此处输入图像描述

Given the UML, I am stuck on how to properly implement the interfaces with the "comparable" keyword.鉴于UML,我被困在如何使用“comparable”关键字正确实现接口上。 Below is a rough implementation of my code.下面是我的代码的粗略实现。 (Abstract class should be correct but interface isn't) (抽象 class 应该是正确的,但接口不是)

interface Bank{
    
    public void institution();

}

abstract Account implements Bank {

    public static int account;

    public void deposit(double amount) {

    }
}

Given that your Account is an abstract class you don't really need to implement the methods in the Interfaces, they must only be implemented by any concrete class.鉴于您的Account是一个抽象的 class,您实际上并不需要实现接口中的方法,它们只能由任何具体的 class 实现。

Nevertheless, if you want to provide a default implementation for both institution() and compareTo(Bank o) methods you can do the following:不过,如果您想为institution()compareTo(Bank o)方法提供默认实现,您可以执行以下操作:

abstract class Account implements Bank {

    public static int account;

    public void deposit(double amount) {

    }

    @Override
    public void institution() {
        // Your logic here
    }

    @Override
    public int compareTo(Bank o) {
        // Your comparison logic here
    }
}

The following is clear from both Bank (three parts, a class) and Comparable (two parts, and interface).从Bank(三个部分,一个类)和Comparable(两个部分,一个接口)都可以清楚地看到以下内容。 The arrows do not conform to full UML.箭头不符合完整的 UML。

public class Bank implements Comparable<Bank>

Bank must implement compareTo so a class is logical.银行必须实现compareTo所以 class 是合乎逻辑的。

That an Account is in any way a Bank does not seem logical (two Accounts being two Banks).一个账户在任何方面都是一个银行似乎不合逻辑(两个账户就是两个银行)。

public abstract class Account {

    public static int globalAccount; // 'account' in diagram.

    public final Bank bank;

    public final int account;

    protected Account(Bank bank) {
        this.bank = bank;
        ++globalAccount; // New account number.
        account = globalAccount;
    }

    public abstract void deposit(double amount);
}

That there should be just one global account value for all I interprete here as a globalAccount for giving a new number to every account.应该只有一个全局account值,我在这里将其解释为globalAccount ,用于为每个帐户提供一个新编号。

The Bank arrow I interprete as field.我将银行箭头解释为字段。 Not really UML.不是真正的UML。


Bank islandBank = new Bank();
Account maryAccount = new IslandAccount();
Account joeAccount = new IslandAccount();
assert(maryAccount.bank == islandBank);
assert(maryAccount.account != joeAccount.account);
maryAccount.deposit(-100);
joeAccount.deposit(100);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM