如何实现无需传入参数即可实例化Monitor子类对象
实现无参构造创建Monitor实例的解决方案
嘿,咱们来把这个问题搞定!先看看你现有的代码,然后一步步调整到能直接无参创建实例的状态。
先理清楚现有问题
你现在的Monitor类已经有一个无参构造,但它只调用了父类的无参构造,而且带参构造里还有个拼写错误(typel应该是type);另外如果不给Monitor自己的字段设置默认值,创建出来的实例会有未初始化的字段(比如type会是null),这显然不太合理。
具体解决方案
1. 先修正代码里的拼写错误
带参构造里的笔误必须改掉,不然编译都通不过:
// 原来的错误写法 this.type = typel; // 修正后 this.type = type;
2. 完善无参构造,初始化子类专属字段
给Monitor的无参构造添加默认值初始化,确保创建出来的实例有合理的初始状态,同时确保父类的无参构造能正常调用:
public class Monitor extends Peripheral { // 先声明Monitor自己的成员变量(你原来的代码里应该有,这里补全) private String type; private int size; private String res; private String ports; // 完善后的无参构造 public Monitor(){ super(); // 调用Peripheral的无参构造,进而触发Product的无参构造 // 给Monitor的字段设置默认值,你可以根据实际需求调整这些值 this.type = "LCD"; this.size = 24; this.res = "1920x1080"; this.ports = "HDMI, VGA"; } // 修正后的带参构造 public Monitor (String name,String maker, int age, int price,String type,int size,String res,String ports){ super(name,maker,age,price); this.type = type; this.size = size; this.res = res; this.ports = ports; } }
3. 确保父类的无参构造存在
因为Monitor的无参构造调用了Peripheral的无参构造,而Peripheral又会自动调用Product的无参构造,所以要保证这两个父类的无参构造可用:
- 如果
Product类没有显式定义任何构造方法,Java会自动提供默认的无参构造,这没问题; - 如果
Product有带参构造,那你必须显式给Product加一个无参构造,比如:
public class Product { protected String name, maker; // 其他字段... // 显式定义无参构造 public Product() { // 可选:给父类字段设默认值,比如this.name = "Unknown Monitor"; this.maker = "Unknown Brand"; } // 你的带参构造... }
- 同理,如果
Peripheral类有带参构造,也要显式添加一个无参构造:
public class Peripheral extends Product { protected int age, price; // 其他字段... // 显式定义无参构造 public Peripheral() { super(); // 调用Product的无参构造 // 可选:给Peripheral的字段设默认值,比如this.age = 0; this.price = 0; } // 你的带参构造... }
最终使用效果
完成以上调整后,你就可以直接用下面的代码创建Monitor实例了,完全不需要传入任何参数:
Monitor myMonitor = new Monitor();
内容的提问来源于stack exchange,提问作者user8603523
相关产品推荐
相关产品推荐

