java - 子构造函数内的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)
还通知没有父构造函数具有这种形状。
当我尝试使用可能需要一些向下转换get
的name
父类方法时,这让我变得复杂,我猜?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()
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)
}
}
推荐阅读
- reactjs - 带有参数的请求,处理和渲染 SPA - 架构方法
- jquery - 使用ajax + jQuery的Laravel分页不起作用
- javascript - 如何从每个绑定内部的 Oracle jet 中的下拉列表中唯一标识所选值
- spring - Spring Boot 与 Cucumber 集成
- javascript - 在 JS 中获得函数后如何重命名对象键
- c++ - C ++按2列对多维数组进行排序
- java - 使用 Guice 的 SparkJava JOOQ 依赖注入
- python - 在 DataFrame 或 CSV 中存储(df.info)方法输出
- php - 将 PHP 字符串值添加到 JSON 数组
- javascript - MongoDB:无法连接到新的副本集主