首页 > 解决方案 > 子构造函数内的Java父级私有属性

问题描述

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

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

public AdMedia(){}


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

当然,它带有公共getter setter变量。

现在问题就出现在我尝试创建一个名为 Magazine 的子类之后。该类应该继承名称和价格,但价格对于每个对象启动都是恒定的。所以他们不会在构造函数上作为名称。

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

我尝试将价格放在构造函数中,但构造函数需要一个传递的参数。Usingsuper(name)还通知没有父构造函数具有这种形状。

当我尝试使用可能需要一些向下转换getname父类方法时,这让我变得复杂,我猜?getName()

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

编辑:我忘了提到我上面写的结果是无法访问杂志名称,所以当我尝试向下转换获取名称时,返回的是空值。

标签: javaparent-childdowncast

解决方案


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

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

推荐阅读