如何更新实例变量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已经定义了这些变量,所以子类中不应包含_paperPrint实例变量。

第二,请看这两行

temp = super.getPaper();   
temp -= paper;

您要减去局部变量temp的值,它与超类中的_print变量无关。您应该致电super.setPaper(temp)来设置_print的值。

,

父类还可以,但是子类和主函数存在一些问题。

  1. 声明子类变量与父类相似是一种不好的做法,因为这会造成混乱。但是,这仍然是合法的,因为父变量对子类是隐藏的。 因此,最好删除:
private String _color; //not used in child class
private int _paper; //not used in child class
  1. 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());
    }
}
  1. 而且由于您要处理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);
    }
    
}