Search code examples
javaabstract-classimplements

Int value does not change after calling method


After calling doReading(),the value of pages is supposed to change, but it does not. Is it possible to do this without declaring int pages; in the MyMath2 and MyScience2 classes. The output should be something like: Before reading: Math- must read 5 pages After reading: Math- must read 3 pages

Abstract Homework2

 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); 
  }


}
}

Interface Processing

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; 
 }
}

Solution

  • Fields are not overridden. This means that the initial pagesToRead won't get updated when doReading() is called, since that method changes pages.

    You should just do:

    public void doReading(){
        setPagesToRead(getPages() - 2);
    }