您如何从另一个类调用构造方法并询问其含义?

时间:2018-12-15 20:05:51

标签: java class methods

这是我尝试将Fruit类中的isCompatibleWith()添加到名为ShoppingCard的类中,并在其中添加addFruit的地方。

  public boolean addFruit(String fruitName,int type, int numItems, int itemWeight) {
     if (toCapacity() == false)
     {
         if (Fruit.isCompatibleWith() == true) //This line does not work.
         {

             return true;
         }
         else
             System.out.println("Cannot add fruit, incompatible with other fruits.");     
     }
     else
         System.out.println("Cannot add fruit, cart is full.");
     return false;}

Fruit.java

    public boolean isCompatibleWith(Fruit other) {
    if (!this.isPerishable() && !other.isPerishable()) // both are non perishable
        return true;
    if (this.isPerishable() != other.isPerishable()) // one is perishable, the other is not
        return false;
    if (this.getType() == other.getType()) // if you've gotten here, both are perishable
        return true;
    return false;
}

1 个答案:

答案 0 :(得分:0)

方法定义为:

public boolean isCompatibleWith(Fruit other)
  • 不是static
    • 因此您需要从Fruit类本身而不是Fruit类的实例中调用它
  • 具有一个Fruit类型的参数:
    • 因此,您需要传递一个Fruit实例以与调用该方法的实例进行比较

  1. 从类内部(如您的代码中),从该类的另一个非静态方法中,您将其命名为

    boolean res = this.isCompatibleWith(otherFruit);
    // or easier : 
    boolean res = isCompatibleWith(otherFruit);
    
  2. 从该类中移除

    Fruit f1 = new Fruit();
    Fruit f2 = new Fruit();
    boolean res = f1.isCompatibleWith(f2);
    

因此,您需要在您的方法中使用其他参数创建一个新的Fruit,然后执行代码:

public boolean addFruit(String fruitName,int type, int numItems, int itemWeight) {
    if (!toCapacity()){
        // change to match your constructor
        Fruit other = new Fruit(fruitName, type, numItems, itemWeight);    
        if (isCompatibleWith(other)){
            //Implement your logic to 'add' the fruit somewhere
            return true;
        }else{
            System.out.println("Cannot add fruit, incompatible with other fruits."); 
        }    
    }else{
         System.out.println("Cannot add fruit, cart is full.");
    }
    return false;
}

布尔提示

  • if(condition == false) ==> if(!condition)
  • if(condition == true) ==> if(condition)