调用方法后int值不改变

Int value does not change after calling method

调用doReading()后,pages的值应该会改变,但实际上并没有。是否可以在不声明 int 页面的情况下执行此操作;在 MyMath2 和 MyScience2 类。输出应该是这样的: 读之前: 数学-必读5页 看完之后: 数学-必读3页

抽象作业2

 public abstract class Homework2 implements Processing
{
  private int pagesToRead;
  private String typeHomework;

 {
    // initialise instance variables
    pagesToRead = 0;
    typeHomework = "none";
 }

 public Homework2(int pages, String hw)
 {
    pagesToRead = pages;
    typeHomework = hw;
 }

 public abstract void createAssignment(int pages);

 public int getPages() 
 {
    return pagesToRead;
 }

 public void setPagesToRead(int p) 
 {
    pagesToRead = p;
 }

 public String getTypeHomework() 
 {
    return typeHomework;
 }

 public void setTypeHomework(String hw)
 {
    typeHomework = hw;
 }

 public String toString() 
 {
    return "reading: \n" + typeHomework + " - must read " + pagesToRead + " pages";
 }

}

TestHomework2

public class TestHomework2
{

public static void main(String []args)
{   

  List<Homework2> tester = new ArrayList<Homework2>();

 tester.add( new MyMath2(5, "Math"));                 
 tester.add( new MyScience2(7, "Science"));


 for (Homework2 c: tester)
  {
    System.out.print("Before ");
    System.out.println(c);
    c.doReading();
    System.out.print("After ");
    System.out.println(c); 
  }


}
}

接口处理

public interface Processing
{
 void doReading()
}

MyMath2

 public class MyMath2 extends Homework2 implements Processing
 {
  int pages; 

 public MyMath2(int pages, String hw)
 {
    super(pages,hw);
 }

 public void createAssignment(int pages) 
 {
    setTypeHomework("Math");
    setPagesToRead(pages);
 }

 public void doReading()
 {
   pages = pages - 2;
 }
 }

MyScience2

public class MyScience2 extends Homework2 implements Processing
{
   int pages;

 public MyScience2(int pages, String hw)
 {
    super(pages,hw);
 }

 public void createAssignment(int pages) 
 {
    setTypeHomework("Science");
    setPagesToRead(pages);
 }

 public void doReading()
 {
  pages = pages - 3; 
 }
}

字段未被覆盖。这意味着初始 pagesToRead 不会在调用 doReading() 时更新,因为该方法更改 pages.

你应该这样做:

public void doReading(){
    setPagesToRead(getPages() - 2);
}
System.out.print("After ");
System.out.println(c); 

class Homework2 的toString()

public String toString() 
{
     return "reading: \n" + typeHomework + " - must read " + pagesToRead + "     pages";
}

你 return pagesToRead。但是在 doReading 中你减少了页面而不是 pagesToRead:

public void doReading()
{
     pages = pages - 2; 
}

减少阅读页数:

public void doReading()
{
     pagesToRead = pagesToRead - 2; 
}

当您通过调用 doReading 更改页数时,您正在更改 MyMath2 对象(MyMath2 对象的 属性)中的页数。您正在打印的数字来自 Homework2.pagesToRead 字段。

当你调用 doReading 方法时,Homework2 中的这个字段永远不会改变,因此你得到相同的值。您可以通过设置您在 MyMath2 对象中设置的值来解决此问题,例如:

public void doReading(){
    pages = pages - 2;
    super.setPagesToRead(pages);
}

或者您从 MyMath2 中完全删除 pages 字段并使用父对象中的字段,例如:

public void doReading(){
    super.setPagesToRead(super.getPagesToRead() - 2);
}

同样适用于 MyScience2 class。