2012-10-06 23 views
0

如果以前曾询问过此问题,但我不知道要搜索什么,所以我很抱歉。Java子类化通用参数

不管怎样,我正在做一个数学包,和许多类的扩展功能:

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; 
} 

} 

我怎样才能做到这一点?

+1

你应该考虑的对象比较空,以避免收到'NPE' – user1406062

+0

这八九不离十看起来像http://stackoverflow.com/questions/tagged/crtp的情况下, - 你可能想看看涉及java的相关问题,如http://stackoverflow.com/questions/2165613/java-generic-type也见:http://en.wikipedia.org/wiki/Talk%3ACuriously_recurring_template_pattern –

+0

你可能只是想'公共抽象类功能' – newacct

回答

1

使用泛型,您可以保证equals方法仅适用于'T'类型,在本例中为'Product'。你不能传递另一个类的类型。

另一种可能性是在CLASSE功能定义:

public abstract boolean equals(Function comparison);

而在CLASSE产品的对象比较蒙山一个comparison instanceof Product

1

覆盖的Object.Equals(Object)方法。这里不需要使用泛型。它的身体会是这个样子

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

return false;