有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我有两个问题

我有一个Apple类,它扩展了一个抽象的Fruit类,请参见下面的代码↓

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

第二个问题:在我的apple构造函数中,我有 String result = seasonal ? "yes" : "no";(我想用boolean打印“Yes”或“No”)是正确的吗?如果是,我怎么做

苹果。爪哇

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

水果。爪哇

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

共 (2) 个答案

  1. # 1 楼答案

    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?

    因为它不在你的水果课上。它位于编译单元的源文件中,其中包括您的水果类。导入应用于包含它的一个源文件中的所有代码

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

    来自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();
        }
    }
    

    这允许您扩展子类中的描述:

     class Apple extends Fruit {
        private AppleVariety appleVariety;
    
        @Override
        public String toString() {
            String description = super.toString();
            description += "\nApple variety: " + appleVariety;
            return description;
        }
     }
    
  2. # 2 楼答案

    第一个问题: 导入不会被继承。仅仅因为你扩展了一个类,它就导入了一些东西,而没有导入那个类的导入。长话短说:你需要把所有你需要的东西都导入一个数据库。java文件

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