在調用doReading()之後,頁面的值應該改變,但不改變。沒有聲明int頁面就可以做到這一點;在MyMath2和MyScience2類中。輸出應該是這樣的: 閱讀之前: MATH-必須閱讀 5頁讀數後: MATH-必須閱讀調用方法後Int值不會改變
3頁摘要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);
}
}
}
接口過程唱
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,是嗎? – Anil 2015-02-07 17:45:09