簡體   English   中英

方法的 Java 接口類型聲明

[英]Java Interfaces type declarations for methods

我有一個包含一些算術運算的接口。 我為復數創建了一個類,它將實現這些操作。

package numeric;
public interface Numeric {

    public void add();
    public void subtract();
    public void multiply();
}

我的班級看起來像這樣

package numeric;
public class Complex implements Numeric {

    private int Re, Im;
    public void add (Complex x){
        this.Re+=x.Re;
        this.Im+=x.Im;  
    }
}

我的方法目前在接口中沒有參數,因為我不知道要制作哪種類型,因為我也必須對分數使用相同的接口。 如果我在類中實現它們時放置Complex ,它會給出一個錯誤,指出該類必須實現所有接口方法。

您可以使用的一種方法是強制每個Numeric子類型相互轉換(有點像Number定義的intValuelongValuedoubleValue等方法,盡管目的略有不同)。

interface Numeric {
    public void add(Numeric other);

    public void subtract(Numeric other);

    public void multiply(Numeric other);

    public Complex toComplex();

    public Fraction toFraction();
}

這有缺點和優點,缺點之一是你的接口現在必須知道它的所有實現(不確定這叫什么,密封類型?)

然后可以按如下方式實現上述內容:

class Complex implements Numeric {

    private int Re, Im;

    @Override
    public void add(Numeric other) {
        Complex complex = other.toComplex();
        this.Re += complex.Re;
        this.Im += complex.Im;
    }

    @Override
    public void subtract(Numeric other) {
        Complex complex = other.toComplex();
        this.Re -= complex.Re;
        this.Im -= complex.Im;
    }

    @Override
    public Complex toComplex() {
        return this;
    }

    @Override
    public Fraction toFraction() {
        //convert to fraction
        return null;
    }
    //rest of the implementation
}

只是附帶說明:通常,此類 API 鼓勵數據結構的不變性,因此建議將其更改為以下內容:

interface Numeric {
    public Numeric add(Numeric other);

    public Numeric subtract(Numeric other);

    public Numeric multiply(Numeric other);

    public Complex toComplex();

    public Fraction toFraction();
}

class Complex implements Numeric {

    private final int re, im;

    public Complex(int re, int im) {
        this.re = re;
        this.im = im;
    }

    @Override
    public Numeric add(Numeric other) {
        Complex complex = other.toComplex();
        return new Complex(this.re + complex.re, this.im + complex.im);
    }

    @Override
    public Numeric subtract(Numeric other) {
        Complex complex = other.toComplex();
        return new Complex(this.re - complex.re, this.im - complex.im);
    }

    @Override
    public Complex toComplex() {
        return this;
    }

    @Override
    public Fraction toFraction() {
        //convert to fraction
        return null;
    }

    //rest of the implementation
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM