Java parent 在 child 构造函数中的私有属性

Java parent's private attribute inside child constructor

标题说明了一切,我得到了一个class其中构造函数的变量必须是私有的

public class AdMedia {
private String name;
private int price;

public AdMedia(){}


public AdMedia(String name, int price) {
    this.name = name;
    this.price = price;
}

当然是自带publicgettersetter的变量。

在我尝试制作一个child class 命名的杂志后,问题就来了。 class 应该继承名称和价格,但是 价格对于每个 object 启动都是不变的。 所以它们不会作为名称出现在构造函数中。

public class Magazine extends AdMedia {
private int area;
private String position;
private String topics;

public Magazine() {}
public Magazine(String name, int size, String position, String topic){

    super();
    this.size = size;
    this.position = position;
    this.topic = topic;

}

它也有自己的 getter setter

我尝试将价格放入构造函数中,但构造函数需要传递参数。使用 super(name) 还通知 parent 构造函数的 none 具有这种形状。

当我尝试使用 parent class 方法 getName() get name 时,这让我很复杂,我猜这可能需要一些向下转换?

我曾尝试寻找解决方案,但大多数都要求我将变量的可访问性更改为 protected。在 private 中没有其他方法可以做到吗?

编辑: 我忘了提一下,我上面写的结果是无法访问杂志名称,所以当我尝试 downcast-get 名称时,返回的是空值。

您可以将您的子构造函数编写为

public Magazine(String name, int size, String position, String topic){
    super();
    setName(name);
    setPrice(100); // 100 is your constant price
    this.size = size;
    this.position = position;
    this.topic = topic;
}

public Magazine(String name, int size, String position, String topic){
    super(name, 100); // 100 is your constant price
    this.size = size;
    this.position = position;
    this.topic = topic;
}

然而,这两种方式都可以在以后更改价格:

Magazine m = new Magazine("name", 50, "position", "topic");
m.setPrice(10);

如果你需要防止这种情况,你也应该覆盖 setPrice() setter:

public class Magazine extends AdMedia {

    ...
    @Override
    public void setPrice(int price) {
        // what to do here?
        // * you could either silently ignore 
        //   (which might surprise some users expecting to be able to change the price)
        // * throw an UnsupportedOperationException 
        //   (which might surprise other users which are not prepared to handle such an exception)
    }
}