子构造函数中的 Java 父级私有属性



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

public class AdMedia {
private String name;
private int price;
public AdMedia(){}

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

当然,这伴随着对变量的公开gettersetter

现在问题就在我尝试制作一个名为 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;
}

这也有自己的gettersetter

我尝试将价格放在构造函数中,但构造函数要求传递参数。使用super(name)还会通知父构造函数都没有这样的形状。

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

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

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

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

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

最新更新