【问题标题】:The field is not visible?字段不可见?
【发布时间】:2022-01-25 04:17:46
【问题描述】:

我在运行这个在 java 中测试继承的程序时遇到问题。我做了两个类,一个应该是父类的 Drink 类,一个应该是子类的 tea 类。我创建了一个构造函数,它使用 super() 调用父构造函数,以创建一个新的茶对象。但是,编译器告诉我,我发送的参数之一 (caloriesPerOunce) 的字段不可见。尽管我不需要将参数包含在 Tea() 的构造函数中,但我确实在稍后的块中声明并实例化了它。这是我的代码的问题,还是因为我使用的是 Eclipse IDE,我应该更改设置?

public class Drink {
    private String name;
    private double quantity;
    private int caloriesPerOunce;
    
    public Drink(String name, double quantity, int caloriesPerOunce)
    {
        this.name = name;
        this.quantity = quantity;
        this.caloriesPerOunce = caloriesPerOunce;
    }
public class Tea extends Drink{
    private boolean isSweet;
    public Tea(String name, double quantity, boolean isSweet)
    {
        super(name, quantity, caloriesPerOunce); //here it tells me that the field Drink.caloriesPerOunce is not visble
        int caloriesPerOunce = 100;
        this.isSweet = isSweet;
    }

【问题讨论】:

  • super(name, quantity, caloriesPerOunce); 在您的具体情况下应该实现什么? caloriesPerOunce 应该被茶所含的卡路里代替,因为在 Tea 中没有定义这样的变量

标签: java inheritance


【解决方案1】:

由于caloriesPerOunce 字段被声明为“Private”,因此除了自身之外没有其他类可以访问它。

换行:

    private int caloriesPerOunce;

到这里:

    public int caloriesPerOunce;

另外,如果你在super() 调用中使用这个参数,你必须先声明它之前的变量,所以这样改变你的 Tea 类:

public class Tea extends Drink {

    private boolean isSweet;

    public Tea(String name, double quantity, boolean isSweet, int caloriesPerOunce) {
        super(name, quantity, caloriesPerOunce);
        this.isSweet = isSweet;
    }
}

你可以这样使用它:

        Drink drink = new Tea("Chocolate", 7, true, 50);

【讨论】:

    【解决方案2】:

    tea 类构造函数没有名为caloriesPerOunce 的参数。您是否尝试从 Drink 父类访问变量,那么由于 caloriesPerOunce 的范围是私有的,所以这将不起作用。如果类是嵌套的,则可以访问 caloriesPerOunce 变量,那么为什么要使用继承呢? https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html

    【讨论】:

      【解决方案3】:

      Java 不是 JavaScript
      简短的回答:不要再假装 Java 是 JavaScript。

      更长的答案:
      在这段代码中:

      super(name, quantity, caloriesPerOunce);
      int caloriesPerOunce = 100;
      

      您 100% 尝试访问父级 caloriesPerOunce 变量。 这是因为您在 super“调用”之后才声明本地 caloriesPerOunce。 在 Java 中(与 JavaScript 不同)没有将变量提升到作用域的顶部。

      如果要将 100 传递给父构造函数,则将 100 传递给父构造函数。

      super(name, quantity, 100);
      

      如果 100 是 Tea 的常数值, 然后您可以为该类声明一个“常量”字段并传递“常量”字段。 例如,

      private static final int TEA_CALORIES = 100;
      
      public Tea(String name, double quantity, boolean isSweet)
      {
          super(name, quality, TEA_CALORIES);
      
          ... other stuff.
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多