Java父的私有属性在子构造函数中的应用

问题描述 投票:0回答:1

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

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 也是。

我试图把价格放在构造函数中,但构造函数要求传递一个参数。使用 super(name) 也通知说没有一个父构造函数有这样的形状。

这让我在尝试使用 getname 使用父类方法 getName() 我想这可能需要一些降频?

我试着搜索了一下解决方案,但大多数都要求我把变量的可访问性改为 protected . 难道就没有其他的方式来完成这个任务吗?private ?

EDIT : 我忘了说,按我上面写的方法做的结果是无法访问杂志名称,所以当我试图降级获取名称时,返回的是一个null。

java parent-child downcast
1个回答
2
投票

你可以把你的子构造函数写成

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() 设置者。

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)
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.