簡體   English   中英

Java子類化通用參數

[英]Java Subclassing Generic Arguments

如果以前曾問過這個問題,我很抱歉,但我真的不知道該搜索什么。

無論如何,我正在制作一個數學包,並且許多類擴展了Function:

package CustomMath;

@SuppressWarnings("rawtypes")
public abstract class Function <T extends Function> {

    public abstract Function getDerivative();

    public abstract String toString();

    public abstract Function simplify();

    public abstract boolean equals(T comparison);

}

我想比較函數,看它們是否相等。 如果它們來自同一個類,我想使用它的特定比較方法,但如果它們是不同的類,我想返回false。 這是我目前的一個課程:

package CustomMath;

public class Product extends Function <Product> {

public Function multiplicand1;
public Function multiplicand2;

public Product(Function multiplicand1, Function multiplicand2)
{
    this.multiplicand1 = multiplicand1;
    this.multiplicand2 = multiplicand2;
}

public Function getDerivative() {
    return new Sum(new Product(multiplicand1, multiplicand2.getDerivative()), new Product(multiplicand2, multiplicand1.getDerivative()));
}

public String toString() {
    if(multiplicand1.equals(new RationalLong(-1, 1)))
        return String.format("-(%s)", multiplicand2.toString());
    return String.format("(%s)*(%s)", multiplicand1.toString(), multiplicand2.toString());
}

public Function simplify() {
    multiplicand1 = multiplicand1.simplify();
    multiplicand2 = multiplicand2.simplify();
    if(multiplicand1.equals(new One()))
        return multiplicand2;
    if(multiplicand2.equals(new One()))
        return multiplicand1;
    if(multiplicand1.equals(new Zero()) || multiplicand2.equals(new Zero()))
        return new Zero();
    if(multiplicand2.equals(new RationalLong(-1, 1))) //if one of the multiplicands is -1, make it first, so that we can print "-" instead of "-1"
    {
        if(!multiplicand1.equals(new RationalLong(-1, 1))) // if they're both -1, don't bother switching
        {
            Function temp = multiplicand1;
            multiplicand1 = multiplicand2;
            multiplicand2 = temp;
        }
    }
    return this;
}

public boolean equals(Product comparison) {
    if((multiplicand1.equals(comparison.multiplicand1) && multiplicand2.equals(comparison.multiplicand2)) || 
            (multiplicand1.equals(comparison.multiplicand2) && multiplicand2.equals(comparison.multiplicand1)))
        return true;
    return false;
}

}

我怎樣才能做到這一點?

使用泛型,您可以保證equals方法僅適用於類型'T',在本例中為'Product'。 你不能傳遞另一種類型。

另一種可能性是在classe函數定義:

public abstract boolean equals(Function comparison);

在classe Product中,對象與產品的comparison instanceof Product進行comparison instanceof Product

覆蓋Object.equals(Object)方法。 您不需要在這里使用泛型。 它的身體看起來像這樣

if (other instanceof Product) {
    Product product = (Product) other;
    // Do your magic here
}

return false;

暫無
暫無

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

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