【问题标题】:Why I have to use sometimes protected and sometimes not?为什么我必须有时使用受保护而有时不使用?
【发布时间】:2021-12-26 09:56:57
【问题描述】:

我有 2 个使用类和类子的不同程序。 在这两个程序中,我都使用私有字段。但是在第一个具有父类“汽车”的程序中,我对私有字段没有任何问题,孩子们可以访问。但是在父类有“汉堡包”的第二个程序中,孩子们不能访问这些字段:

第一个程序程序正在运行

public class Car {
    private boolean engine;
    private int cylinders;
    private String name;
    private int wheels;

    public Car(int cylinders, String name) {
        this.cylinders = cylinders;
        this.name = name;
        this.wheels = 4;
        this.engine = false;
    }
}


public class Mitsubishi extends Car {
    public Mitsubishi() {
        super(5, "Mitsubishi");
    }
}
 

第二个程序不工作

public class Hamburger {
    private String name;
    private String meat;
    private double price;
    private String breadRollType;
    private String addition1;
    private String addition2;
    private String addition3;
    private String addition4;


    public Hamburger(String name, String meat, double price, String breadRollType) {
        if (price < 0) {
            price = 0;
        }
        this.name = name;
        this.meat = meat;
        this.price = price;
        this.breadRollType = breadRollType;
        this.addition1 = "none";
        this.addition2 = "none";
        this.addition3 = "none";
        this.addition4 = "none";
    }
}

public class DeluxeBurger extends Hamburger{
    public DeluxeBurger() {
        super("Deluxe Burger", "Steak", 19.10, "Chic bread");
    }
}

我已经看到我可以使用 protected 并且它修复了问题,但我不知道为什么我必须在第二个程序上使用 protected(使用汉堡包)但不是第一个(与汽车一起)。

【问题讨论】:

  • 程序 #2 中究竟有什么问题?
  • 当我想用 DeluxeBurger 类(子类)中的构造函数创建一个新 Object 时,错误提示该字段在 Hamburger(父类)中具有私有访问权限。
  • 哪个字段?你能复制粘贴确切的错误信息吗?
  • 这两个类是在同一个包上吗?调用这个的文件怎么样?
  • DeluxeBurger 不访问这些字段,您确定这是您的代码吗?

标签: java class


【解决方案1】:

我将您的代码复制到我的项目中并查看您的问题。 我不知道为什么,也许它是一个错误。但是如果您创建新包并将这两个类放入新包中,您的问题将得到解决,您将不会再看到此问题。这对我来说很有趣。 谢谢

【讨论】:

  • 如果这对您不起作用,请创建新包并删除该类并再次创建类。它对我有用
  • 我已经通过创建新包进行了测试,但是我在新包中也出现了这个错误
  • 我所做的正是将类移动到正确的包中,然后将其修复。这就是为什么我要求你一次删除整个类并在另一个包中重建它
  • 我使用 IntelliJ 的折射器选项来移动类,但我又遇到了错误
  • 可能是我使用 intellij idea 及其工作的开发环境中的一个错误
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-08-25
  • 2012-02-02
  • 2010-09-16
  • 1970-01-01
  • 2017-03-10
  • 2022-01-26
  • 2022-06-11
相关资源
最近更新 更多