Wednesday, April 8, 2015

Sample: LibraryCard

LibraryCard.java,  Librarian.java

/*
    Introduction to OOP with Java (5th Ed), McGraw-Hill

    Wu/Otani

    File: LibraryCard.java

*/

class LibraryCard {

    // Data Members  
   
    //student owner of this card
    private Student owner;
   
    //number of books borrowed
    private int borrowCnt;
   
    //numOfBooks are checked out
    public void checkOut(int numOfBooks) {
        borrowCnt = borrowCnt + numOfBooks;
    }
   
    //Returns the name of the owner of this card
    public String getOwnerName( ) {
        return owner.getName( );
    }
   
    //Returns the number of books borrowed
    public int getNumberOfBooks( ) {
        return borrowCnt;
    }
   
    //Sets the owner of this card to student
    public void setOwner(Student student) {
        owner = student;
    }
   
   
    //Returns the string representation of this card
    public String toString( ) {
        return  "Owner Name:     " + owner.getName( ) + "\n" +
                "      Email:    " + owner.getEmail( ) + "\n" +
                "Books Borrowed: " + borrowCnt;
    }
      
 }

//-----------------


/*
    Introduction to OOP with Java (5th Ed), McGraw-Hill

    Wu/Otani

    File: Librarian.java

*/

class Librarian {
  
    public static void main( String[] args ) {
   
        Student    student;
        LibraryCard card1, card2;
       
        student = new Student( );
        student.setName("Jon Java");
        student.setEmail("jj@javauniv.edu");
       
        card1 = new LibraryCard( );
        card1.setOwner(student);
        card1.checkOut(3);
       
        card2 = new LibraryCard( );
        card2.setOwner(student); //the same student is the owner
                                 //of the second card, too
       
        System.out.println("Card1 Info:");
        System.out.println(card1.toString() + "\n");
       
        System.out.println("Card2 Info:");
        System.out.println(card2.toString() + "\n");
      
    }

}

No comments:

Post a Comment