1

我正在尝试构建包含继承的类。我创建的课程

  1. 主要的

  2. 项目清单

  3. 图书馆

  4. 物品

  5. 图书

  6. 音乐CD

  7. 电影

  8. 杂志...等

这是图书馆类

    import java.util.ArrayList;

    public class Library {
    /**
    * itemList contains the List of all items in the library. 
    */
private ArrayList itemList;

/**
 * count of all the items in the library. 
 */
private int count;

public Library(){

}

/**
 * Add a new item to the list of items. 
 * @param newItem The new item to be added to the list.
 * @throws unisa.library.DuplicateItemException
 */

public void addItem(Item newItem) throws DuplicateItemException {
    itemList.add(newItem);
}

}

物品类别,

    public class Item extends Person{
private String id;
private String name;
private boolean loaned;
//borrower?
private double cost;


public Item(String id, String name, boolean loaned, String borrower, double cost) {
    // TODO Auto-generated constructor stub
    super(borrower);
    this.id = id;
    this.name=name;
    this.loaned = loaned;
    this.cost = cost;
}

public String getID(String id){
    return id;
}
public String getName(String name){
    return name;
}
public boolean getLoaned(boolean loaned){
    return loaned;
}
public double getCost(double cost){
    return cost;
}

}

人班,

    public class Person {

private String name;
private String address;
public Person(String name, String address){

    this.name = name;
    this.address = address;
}
public Person(String name){
    this.name = name;
}

}

书、电影、MusicCD 都是一样的

    public class Book extends Item{
private String author;

public Book(String author, String id, String name, boolean loaned, String borrower, double cost){
    super(id, name, loaned, borrower, cost);
    this.author = author;
}

}

我必须使用这些类,但我不确定我是否应用了正确的继承。

现在问题出在他们正在启动库对象的主类上

做测试

    Library l1 = new Library();

和调用方法

    l1.addItem(new Magazine(Magazine.frequency.day, "ID001","Vanity Not So Faire",      false,"New York", null, 5.95));

在这里,他们传递 Magazine 类的对象(与 book 类相同),并且在函数声明中我使用 Item 作为容器。通过 addItem 需要添加任何项目(书籍、杂志、DVD ...等)。我应该在函数声明中传递什么容器(addItem(?))或者结构化类有什么问题???

4

4 回答 4

1

继承视为“IS A(N)”关系;将组合视为“HAS A(N)”关系。

通俗地说,每本书、电影、音乐 CD 等都是一个项目。

图书馆有书、电影等;更准确地说,图书馆有一系列物品。

根据你的实现,你也可以说一个人有一组物品,而图书馆有一组人(例如顾客或顾客)。如上所示,一个人还有姓名和地址等个人详细信息。


话虽如此,您将使用上面定义的继承和组合来构造您的类。您生成的类可能如下所示(仅显示字段和超类,让您了解如何相应地使用继承和组合):

class Library {
  Collection<Item> items;
  Collection<Person> customers;
}

class Person {
  Collection<Item> items;
  String name;
  String address;
}

class Item {
  String id;
  String name;
  // etc.
}

class Book extends Item {
  String author;
}

class MusicCD extends Item {
  String artist;
}

// etc.
于 2013-10-23T06:33:52.757 回答
0

我注意到错误的第一件事是为什么Item扩展一个Person..?

下一个是,如果书籍、杂志和你所说的所有其他东西都有相同的代码,它就破坏了可重用性的概念。

所以,总结一下

Person 类不需要由任何其他类扩展,但由于他可以借用一个项目,因此他可能在该类中有 Item 的引用

public class Person {
  private ArrayList<Item> itemList;
  //more person specific code
}

Item 类可以有一个 Person 引用,例如

public class Item {
  Person borrower;
  //More Item specific code
}

item 应该由一个类扩展Media,然后你可以构造继承该类的专用Media类。

public class Media extends Item {
  //media specific code
}


public class Movie extends Media {
  public enum Quality {FULL_HD, HD};
  //more Movie specific code
}

这可能会给你一个小想法..

于 2013-10-23T06:37:19.633 回答
0

感谢您的回答,但问题是类结构是固定的,我只需要为给定函数编写代码并将继承应用于相关类。还有一个 testdriver 类可以测试所有其他类及其执行,所以我需要根据 testdriver 类编写代码。

1)TestDriver类

    public class TestDriver {

public void runTestAddItem() {      
    System.out.println("***Testing addItem***");

    //by putting {} around each test we throw away all the variables created inside the braces when you get to the end of the test.   
    //Like a self cleaning mode.
    {
        System.out.println("-Test add an item and see if it is in the list-");
        String expected = "Found";
        System.out.println("Expected <"+expected+">");
        //Do the Test
        Library l1 = new Library();
        Item retrieved = null;
        String result = "";
        try {
            l1.addItem(new Magazine(Magazine.frequency.day, "ID001","Vanity Not So Faire", false,"New York", null, 5.95));
            retrieved = l1.findItem("ID001");
            //This will always come out true in this test as if there is an exception it will skip this line anyway.
            //It is in here for completeness and if someone writes another tests and uses this as an example.
            //The findItem should never return null but this will cover an event when something goes wrong in the library code 
            result = retrieved != null? "Found":"Not Found";
        } catch (DuplicateItemException e) {
            result = "Failed Duplicate Found";
        } catch (Exception e) {
            result = "Failed Exception Thrown";
        }           
        System.out.println("Got <"+result+">"); 
        if (result.equals(expected)) {
            System.out.println("Success");
        } else {
            System.out.println("Failed");
        }
    }

    {
        System.out.println("-Test add an item with a duplicate see if it throws an exception-");
        String expected = "Failed Duplicate Found";
        System.out.println("Expected <"+expected+">");
        //Do the Test
        Library l1 = new Library();
        Item retrieved = null;
        String result = "";
        try {
            l1.addItem(new Magazine(Magazine.frequency.day, "ID001","Vanity Not So Faire", false, "New York",null, 5.95));
            l1.addItem(new Magazine(Magazine.frequency.day, "ID001","Vanity Not So Faire", false,"New Jersey", null, 5.95));
            retrieved = l1.findItem("ID001");
            result = retrieved != null? "Found":"Not Found";
        } catch (DuplicateItemException e) {
            result = "Failed Duplicate Found";
        } catch (Exception e) {
            result = "Failed Exception Thrown";
        }           
        System.out.println("Got <"+result+">"); 
        if (result.equals(expected)) {
            System.out.println("Success");
        } else {
            System.out.println("Failed");
        }
    }

    //You need to write lots of tests here. 

}


public void runTestAddBorrower() {
    System.out.println("***Testing addBorrower***");
    {
        //use the first test as a template on how to write more
    }

}



public void runTestCountBorrowed() {
    System.out.println("***Testing countBorrowed***");

}



public static void main(String[] args) {
    TestDriver td = new TestDriver();

    td.runTestAddItem();
    td.runTestAddBorrower();
    td.runTestCountBorrowed();
    //you need to add more


    td.arbitraryTestCode();
}



/**
 * This method just contains some dummy test code to check that basic functionality is working and also fail if the API is not created correctly in the Library file and Item file.



*/

    public void arbitraryTestCode() {
    Library l1 = new Library();
    Person p1 = null;
    try {
        p1 = new Person("Stewart","Mawson Lakes Blvd");
    } catch (Exception e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }   
    int id=0;
    try {
        Item[] testSubjects = {
                new Magazine(Magazine.frequency.day, "ID00"+id++,"Vanity Not So Faire", false, "San Andreas",null, 5.95),
                new Magazine(Magazine.frequency.day, "ID00"+id++,"Click", false, "San Andreas",null, 5.95),
                new Magazine(Magazine.frequency.day, "ID00"+id++,"Renovate", false, "San Andreas",null, 5.95),
                new Magazine(Magazine.frequency.day, "ID00"+id++,"Madrid", false, "San Andreas",null, 5.95),
                new Magazine(Magazine.frequency.day, "ID00"+id++,"Bikes", false, "San Andreas",null, 5.95),
                new MusicCD("Rudy Vale","Valen","ID00"+id++,"Gatewars Soundtrack",false,null,19.95),
                new MusicCD("Rudy Vale The Third","Valen","ID00"+id++,"Gatewars 2 Soundtrack",false,null,19.95),
                new MusicCD("Rudy Vale Sr","Valen","ID00"+id++,"Gatewars 3 Soundtrack",false,null,19.95),
                new MusicCD("Rudy Vale Jr","Valen","ID00"+id++,"Gatewars 4 Soundtrack",false,null,19.95),
                new MusicCD("Not Rudy Vale","Valen","ID00"+id++,"Gatewars 5 Soundtrack",false,null,19.95),
                new MusicCD("Rudy Vale","Not Valen","ID00"+id++,"Gatewars 6 Soundtrack",false,null,19.95),
                new Bluray('c',Bluray.genre.drama,"ID00"+id++,"Gatewars 1 Revenge of the Fallen",false,null,29.95),
                new Bluray('c',Bluray.genre.drama,"ID00"+id++,"Gatewars 2 Ponies Are Ridden",false,null,29.95),
                new Bluray('c',Bluray.genre.drama,"ID00"+id++,"Gatewars 3 Sequels are Lame",false,null,29.95),
                new Bluray('c',Bluray.genre.drama,"ID00"+id++,"Gatewars 3 But They Keep Making Them",false,null,29.95),
                new Bluray('c',Bluray.genre.drama,"ID00"+id++,"Gatewars 5 They Make More Than is Reasonable",false,null,29.95),
                new DVD(1,DVD.genre.scifi,"ID00"+id++,"Darth Yobbit and the Range Runners",false,null,29.95),
                new DVD(1,DVD.genre.scifi,"ID00"+id++,"Darth Yobbit and the Long Jumpers",false,null,29.95),        
                new DVD(1,DVD.genre.scifi,"ID00"+id++,"Darth Yobbit and the Domain Walkers",false,null,29.95),      
                new DVD(1,DVD.genre.scifi,"ID00"+id++,"Darth Yobbit and the KiloByte",false,null,29.95),        
                new DVD(1,DVD.genre.scifi,"ID00"+id++,"Darth Yobbit and the Rabbits",false,null,29.95),     
                new Book("Arthur C Clarke","ID00"+id++,"The City and The Stars",false,null,14.50),
                new Book("Arthur C Clarke","ID00"+id++,"Rendevous With Rama",false,null,14.50),
                new Book("Arthur C Clarke","ID00"+id++,"2001",false,null,14.50)
        };

        for (int i=0;i<testSubjects.length;i++) {
            try {
                l1.addItem(testSubjects[i]);
            } catch(DuplicateItemException ex) {
                System.err.println(ex);
            }
        }
        System.out.println("******");

        System.out.println(l1);
        l1.loanItem("ID0022", new Person("Stewart","Mawson Lakes"));
        System.out.println("Should say false "+l1.isBorrowed("ID0020"));
        System.out.println("Should say true "+l1.isBorrowed("ID0022"));
        System.out.println("Should say Stewart " + l1.getBorrower("ID0022").getName());
        System.out.println("Should say Mawson Lakes " + l1.getBorrower("ID0022").getAddress());

        System.out.println("******");

        //Various get datas from items
        System.out.println(l1.findItem("ID0020").getName());
        System.out.println(l1.findItem("ID0020").getId());
        System.out.println(l1.findItem("ID0020").getCost());
        System.out.println(l1.findItem("ID0020").getBorrower());
        System.out.println("Should be false "+l1.findItem("ID0020").isLoaned());
        l1.findItem("ID0020").setBorrower(new Person("AAA","ADDRESS"));
        //Corrected this.   BTW in normal operation this should not occur that there
        //is a borrower but not loaned.  This code is here to ensure that you have all 
        //The appropriate methods I need to check your code later.
        System.out.println("Should be false "+l1.findItem("ID0020").isLoaned());
        l1.findItem("ID0020").setCost(99.99f);
        l1.findItem("ID0020").setLoaned(false);
        l1.findItem("ID0020").setName("Changed Name");
        System.out.println(l1.findItem("ID0020"));

        System.out.println("******");


        try {
            System.out.println(l1.findItem("ID006"));
        } catch (ItemNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        System.out.println("******");

        System.out.println("Number Borrowed "+l1.countBorrowed());
        System.out.printf("Percentage Borrowed %5.2f%% \n",l1.percentageBorrowed());
        try {
            l1.loanItem("ID001", p1);
            l1.loanItem("ID003", p1);
            l1.loanItem("ID004", p1);
            l1.loanItem("ID009", p1);
        } catch (ItemNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("******");


        System.out.println("Number Borrowed Should say 5 "+l1.countBorrowed());
        System.out.printf("Percentage Borrowed %5.2f%% \n",l1.percentageBorrowed());

        System.out.println("Should say 10 "+l1.countMovies());
    } catch (Exception ex) {
        System.err.println("Exception Found in Input "+ex.getMessage());
    }

}
    }
此方法应输出
杂志 [magazineFrequency=day, distributionCity=San Andreas, toString()=Item [id=ID000, name=Vanity Not So Faire, loaned=false, borrower=null, cost=5.95]]
杂志 [magazineFrequency=day, distributionCity=San Andreas, toString()=Item [id=ID001, name=Click, loaned=false, borrower=null, cost=5.95]]
杂志 [magazineFrequency=day, distributionCity=San Andreas, toString()=Item [id=ID002, name=Renovate, loaned=false, borrower=null, cost=5.95]]
杂志 [magazineFrequency=day, distributionCity=San Andreas, toString()=Item [id=ID003, name=Madrid, loaned=false, borrower=null, cost=5.95]]
杂志 [magazineFrequency=day, distributionCity=San Andreas, toString()=Item [id=ID004, name=Bikes, loaned=false, borrower=null, cost=5.95]]
MusicCD [作曲家=Rudy Vale, 艺术家=Valen, toString()=Item [id=ID005, name=Gatewars Soundtrack, loaned=false, borrower=null, cost=19.95]]
MusicCD [作曲家=Rudy Vale The Third, 艺术家=Valen, toString()=Item [id=ID006, name=Gatewars 2 Soundtrack, loaned=false, borrower=null, cost=19.95]]
MusicCD [作曲家=Rudy Vale Sr, 艺术家=Valen, toString()=Item [id=ID007, name=Gatewars 3 Soundtrack, loaned=false, borrower=null, cost=19.95]]
MusicCD [作曲家=Rudy Vale Jr, 艺术家=Valen, toString()=Item [id=ID008, name=Gatewars 4 Soundtrack, loaned=false, borrower=null, cost=19.95]]
MusicCD [作曲家=Not Rudy Vale, 艺术家=Valen, toString()=Item [id=ID009, name=Gatewars 5 Soundtrack, loaned=false, borrower=null, cost=19.95]]
MusicCD [作曲家=Rudy Vale,艺术家=Not Valen,toString()=Item [id=ID0010,name=Gatewars 6 原声带,借出=假,借入者=null,成本=19.95]]
Bluray [region=c, toString()=Movie [genre=drama, toString()=Item [id=ID0011, name=Gatewars 1 Revenge of the Fallen, loaned=false, borrower=null, cost=29.95]]]
Bluray [region=c, toString()=Movie [genre=drama, toString()=Item [id=ID0012, name=Gatewars 2 Ponies Are Ridden, loaned=false, borrower=null, cost=29.95]]]
Bluray [region=c, toString()=Movie [genre=drama, toString()=Item [id=ID0013, name=Gatewars 3 Sequels are Lame, loaned=false, borrower=null, cost=29.95]]]
Bluray [region=c, toString()=Movie [genre=drama, toString()=Item [id=ID0014, name=Gatewars 3 但他们一直在制作它们,借出=假,借入者=null,成本=29.95]]]
Bluray [region=c, toString()=Movie [genre=drama, toString()=Item [id=ID0015, name=Gatewars 5 他们赚的比合理的多,借出=假,借入者=空,成本=29.95]] ]
DVD [region=1, toString()=Movie [genre=scifi, toString()=Item [id=ID0016, name=Darth Yobbit and the Range Runners, loaned=false, borrower=null, cost=29.95]]]
DVD [region=1, toString()=Movie [genre=scifi, toString()=Item [id=ID0017, name=Darth Yobbit and the Long Jumpers, loaned=false, borrower=null, cost=29.95]]]
DVD [region=1, toString()=Movie [genre=scifi, toString()=Item [id=ID0018, name=Darth Yobbit and the Domain Walkers, loaned=false, borrower=null, cost=29.95]]]
DVD [region=1, toString()=Movie [genre=scifi, toString()=Item [id=ID0019, name=Darth Yobbit and the KiloByte, loaned=false, borrower=null, cost=29.95]]]
DVD [region=1, toString()=Movie [genre=scifi, toString()=Item [id=ID0020, name=Darth Yobbit and the Rabbits, loaned=false, borrower=null, cost=29.95]]]
书 [作者=Arthur C Clarke, toString()=Item [id=ID0021, name=The City and The Stars, loaned=false, borrower=null, cost=14.5]]
书 [作者=Arthur C Clarke, toString()=Item [id=ID0022, name=Rendevous With Rama, loaned=false, borrower=null, cost=14.5]]
书 [作者=Arthur C Clarke, toString()=Item [id=ID0023, name=2001, loaned=false, borrower=null, cost=14.5]]

应该说假假
应该说真真
应该说斯图尔特斯图尔特
应该说莫森湖莫森湖
     ******
达斯·约比特和兔子
ID0020
29.95
无效的
应该是假的假的
应该是假的假的
DVD [region=1, toString()=Movie [genre=scifi, toString()=Item [id=ID0020, name=Changed Name, loaned=false, borrower=Person [name=AAA, address=ADDRESS, toString() =unisa.library.Person@24a37368],成本=99.98999786376953]]]
     ******
MusicCD [作曲家=Rudy Vale The Third, 艺术家=Valen, toString()=Item [id=ID006, name=Gatewars 2 Soundtrack, loaned=false, borrower=null, cost=19.95]]
     ******
借来的号码 1
借入百分比 4.17%
     ******
借来的数字应该说 5 5
借贷比例 20.83%
应该说 10 10

2) 在库类中,需要对项目使用 ArrayList,

    public class Library {

    /**
    * itemList contains the List of all items in the library. 
    */
private ArrayList itemList;

/**
 * count of all the items in the library. 
 */
private int count;

public Library(){

}

/**
 * Add a new item to the list of items. 
 * @param newItem The new item to be added to the list.
 * @throws unisa.library.DuplicateItemException
 */

public void addItem(Item newItem) throws DuplicateItemException {
    itemList.add(newItem);
}

/**
 * Return the total number of items out on loan. 
 * @return The number representing the number of items currently on loan
 */

public int countBorrowed(){

    return 0;

}

/**
 * Return the number of Items that are either Blurays or DVDs 
 * @return the number of blurays and DVDs
 */
public int countMovies(){

    return 0;
}

/**
 * Find the item by the given ID and return that Item 
 * @param id The item to be returned
 * @return The item searched for.
 * @throws unisa.library.ItemNotFoundException thrown if the id is not found.
 */
public Item findItem(String id) throws ItemNotFoundException{

    return null;
}


/**
 * Gets the borrower of an item. If the item is not found throw ItemNotFoundException. 
 * @param id 
 * @return the borrower of the item. returns null if the item exists but is not borrowed.
 * @throws unisa.library.ItemNotFoundException thrown if the id is not found
 */
public Person getBorrower(String id) throws ItemNotFoundException{

    return null;
}


/**
 * Return the id of the given name. 
 * @param name the name of the item
 * @return the id of the item blank if not found.
 */
public String IDForName(String name){

    return null;
}


/**
 * Checks if a specific item is borrowed. 
 * @param id The id of the item that is to be checked.
 * @return the status of the item whether it is borrowed or not.
 * @throws unisa.library.ItemNotFoundException thrown if the id is not found.
 */
public boolean isBorrowed(String id) throws ItemNotFoundException{

    return false;
}


/**
 * Changes the status of the named item to borrowed and adds the Person to the borrowed
 * @param id The ID of the item to be borrowed
 * @param newPerson The borrower of the item
 * @throws unisa.library.ItemNotFoundException thrown if the id is not found.
 */
public void loanItem(String id, Person newPerson) throws ItemNotFoundException{

}

/**
 * Look up the name of the item based on the ID given. 
 * @param id The id of item searched for.
 * @return The name of the item blank if not found.
 */
public String nameForID(String id){

    return null;
}

/**
 * The percentage of the number of items that are out on loan. Expressed as a percentage of borrowed to total number of items.
 * @return the percentage borrowed.
 */
public double percentageBorrowed(){
    return 0;
}

/**
 * Changes the status of the named item to not borrowed and removes the user from the item. The borrower (person) is returned to the caller
 * @param id The id of the item
 * @return The person who borrowed the item
 * @throws unisa.library.ItemNotFoundException
 */
public Person returnItem(String id) throws ItemNotFoundException{
    return null;
}

    }

据此,我已经形成了 Item 类

2)项目类有一个构造函数,其中有借款人的姓名,所以我应该分配这个值。

    public class Item{
private String id;
private String name;
private boolean loaned;
private Person borrower;
private double cost;


public Item(String id, String name, boolean loaned, String borrower, double cost) {
    // TODO Auto-generated constructor stub
    //borrower; ??
    this.id = id;
    this.name=name;
    this.loaned = loaned;
    this.cost = cost;
}

public String getID(String id){
    return id;
}
public String getName(String name){
    return name;
}
public boolean getLoaned(boolean loaned){
    return loaned;
}
public double getCost(double cost){
    return cost;
}




    }
于 2013-10-24T07:29:21.250 回答
0

您应该从 Person 类开始。这不应该扩展任何东西。然后,您应该使用包含项目列表和人员列表的基类库(如果需要)。然后是项目类。然后是应该扩展项目类的书类。同样,MusicCD、Movie、Magazine 应该扩展项目类。

于 2013-10-23T06:25:41.427 回答