java - 如何更新实例变量JAVA的值
问题描述
我是 JAVA 和 OOP 的新手,我正在尝试做一些 OOP 练习,但坚持更新晚餐类的实例变量的值。
我有一个名为 Print 的超类
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!");
}
}
和一个子类 ColorPrint
public class ColorPrint extends Print {
private String _color;
private int _paper;
public ColorPrint(int paper, String color) {
super(paper, color);
}
// runPrint
@Override
public void runPrint(int paper) {
int temp = 0;
if(super.getPaper() - paper < 0) {
paper -= super.getPaper();
System.out.println(super.getColor() + " paper needs " + paper + " more!");
} else {
System.out.println(super.getColor() + " " + super.getPaper() + " is printed.");
temp = super.getPaper();
temp -= paper;
System.out.println(super.getColor() + " is remains for " + temp);
}
return;
}
// addPaper
@Override
public void addPaper(int paper) {
System.out.println(paper + " is added.");
int currPaper = super.getPaper() + paper;
super.setPaper(currPaper);
}
@Override
public String toString() {
return super.getColor() + ": " + "current paper is " + super.getPaper();
}
}
和主要功能
public static void main(String[] args) {
Print[] p = {
new ColorPrint(100, "Color")
};
// print out the available 100 papers
// after printed the current paper now is zero.
p[1].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[1].addPaper(50);
}
我的问题是如何在减法和加法后更新晚餐类中实例变量 paper 的值?
谢谢你。
解决方案
首先,你不应该在子类中有一个_color
和_paper
实例变量,因为父类Print
已经定义了这些变量。
其次,看这两条线
temp = super.getPaper();
temp -= paper;
您正在减去局部变量的值,它与超类中temp
的变量无关。_print
你应该打电话super.setPaper(temp)
来设置_print
.
推荐阅读
- php - 意外的开始标签(正文)html
- java - 重定向阻塞异常
- javascript - html onclick 事件:如何根据提供给 onclick 的参数更新值
- r - 基于总列值比例的子集 R 数据框
- c++ - C++ 过程入口点错误
- javascript - YouTube 视频:适合非 16:9 父亲的内容(背景尺寸:封面)
- reactjs - 如何只允许使用 Flow 和 React 的特定元素类型作为子元素?
- nlog - nlog.etw 扩展不发出 ETW
- oracle - 一张表上的分层多重更新查询 - oracle
- esp8266 - 74880 波特的 ESP8266 错误消息