为什么我必须在我的子类中使用导入,而它已经在超类中了?

Why do I have to use an import in my subclass, when it's already in the superclass?

我有两个问题。

我有一个 Apple class 扩展了一个抽象的 Fruit class 见下面的代码 ↓

第一个问题:为什么我必须在我的苹果class中使用import java.awt.Color; ,因为它已经在我的水果class中了?我得到一个错误:找不到符号

第二个问题:在我的苹果构造函数中,我有 String result = seasonal ? "yes" : "no";(我希望布尔值打印 "Yes" 或 "No")是正确的,在 Fruit 布尔方法中会更好还是public static void 主要?如果是,我该怎么做?

Apple.java

import food.Fruit;
import java.awt.Color;

class Apple extends Fruit {

  public static void main(String args[]) {
    Fruit apple = new Apple(Color.RED, true);
    apple.prepare();
    System.out.println("Color: " + apple.getColor());
  }

  public Apple(Color color, boolean seasonal) {
    super(color, seasonal);
    String result = seasonal ? "yes" : "no";
    System.out.println("Seasonal: " + result);
  }

  @Override
  public void prepare() {
    System.out.println("Cut the Apple");
  }
}

Fruit.java

package food;

import java.awt.Color;

public abstract class Fruit {
  private Color color;
  private boolean seasonal;

  public Fruit(Color color, boolean seasonal) {
    this.color = color;
    this.seasonal = seasonal;
  }

  public abstract void prepare();

  public Color getColor() {
    return color;
  }

  public boolean isSeasonal() {
    return seasonal;
  }
}

第一个问题: 导入不会被继承。只是因为您扩展了 class,所以导入的内容不会导入 class 的导入内容。长话短说:您需要在 .java 文件中导入所需的所有内容。

第二个问题: 只要有可能并且合理,将代码从子classes 移到父classes。这减少了代码重复。

First question: Why do I have to use the import java.awt.Color; in my apple class, since it's already in my Fruit class?

因为它不在你的水果里class。它位于 编译单元 -- 源文件中,其中包含你的 Fruit class。导入适用于包含它的一个源文件中的所有代码。

导入不被继承,因为源文件没有继承。

来自 Java 语言规范,section 7.5: Import declarations:

An import declaration makes types or members available by their simple names only within the compilation unit that actually contains the import declaration.

关于问题 2 ...

Second question: in my apple constructor I have String result = seasonal ? "yes" : "no"; (I want boolean to print "Yes" or "No") is that right would it be better in the Fruit boolean method or public static void main? If yes how do I do that?

你有这两行:

String result = seasonal ? "yes" : "no";
System.out.println("Seasonal: " + result);

第二行最好放在 Fruit.isSeasonal()Apple() 构造函数中。在这些函数中,打印将是一个副作用,某些调用者可能不需要。

将此代码包含在 Apple.main() 中是合理的。

另一种可能性是定义一个toString()或类似的方法来构建描述,然后在任何你喜欢的地方打印描述。

public abstract class Fruit  
    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append( "Color: " + color.toString() );

        String result = seasonal ? "yes" : "no";
        builder.append("\nSeasonal: " + result);

        return builder.toString();
    }
}

这允许您扩展子classes:

中的描述
 class Apple extends Fruit {
    private AppleVariety appleVariety;

    @Override
    public String toString() {
        String description = super.toString();
        description += "\nApple variety: " + appleVariety;
        return description;
    }
 }