如何解决如何更新实例变量JAVA的值
我是JAVA和OOP的新手,我试图做一些OOP练习,但是坚持更新supper类的实例变量的值。
我有一个叫做Print的超类
async
和一个子类ColorPrint
await
和主要功能
public class Print {
private String _color;
private int _paper;
public Print(int paper,String color) {
this._color = color;
this._paper = paper;
}
// getter
public String getColor() {
return this._color;
}
public int getPaper() {
return this._paper;
}
// getter
public void setColor(String color) {
this._color = color;
}
public void setPaper(int paper) {
this._paper = paper;
System.out.println("current amount of paper: " + this._paper);
}
// runPrint
public void runPrint(int paper) {
System.out.println("this is demo!");
return;
}
// addPaper
public void addPaper(int paper) {
System.out.println("this is demo!");
}
}
我的问题是,减去和添加后,如何更新晚餐类中实例变量paper的值?
谢谢。
解决方法
首先,因为父类_color
已经定义了这些变量,所以子类中不应包含_paper
和Print
实例变量。
第二,请看这两行
temp = super.getPaper();
temp -= paper;
您要减去局部变量temp
的值,它与超类中的_print
变量无关。您应该致电super.setPaper(temp)
来设置_print
的值。
父类还可以,但是子类和主函数存在一些问题。
- 声明子类变量与父类相似是一种不好的做法,因为这会造成混乱。但是,这仍然是合法的,因为父变量对子类是隐藏的。 因此,最好删除:
private String _color; //not used in child class
private int _paper; //not used in child class
-
runPrint
方法
@override
public void runPrint(int paper) {
if(paper > super.getPaper()) {
int requiredPapers = paper - super.getPaper());
System.out.println(super.getColor() + " paper needs " + requiredPapers + " more!");
} else {
System.out.println(super.getColor() + " " + super.getPaper() + " is printed.");
super.setPaper(super.getPaper() - paper); // HERE use setter/mutator method
System.out.println(super.getColor() + " is remains for " + super.getPaper());
}
}
- 而且由于您要处理
Print
数组,因此循环很方便。
public static void main(String[] args) {
Print[] p = { new ColorPrint(100,"Color") };
for(int i = 0; i < p.length; i++) {
// print out the available 100 papers
// after printed the current paper now is zero.
p[i].runPrint(100);
// then I add 50 papers
// the current paper now must be 50.
// But it prints out 150. I'm stuck on this.
p[i].addPaper(50);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。