【发布时间】: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不访问这些字段,您确定这是您的代码吗?