11/2/2011

Construction, Encapsulation, and Instance Methods

CSC116: Intro to Java Programming © Sarah Heckman 1

Outline

•The Hunt Library – current state • Constructors •Encapsulation • General Class Syntax •Class Invariants • Additional Instance Methods •Exercise 29

CSC116: Intro to Java Programming © Sarah Heckman 2

1 11/2/2011

Hunt Library Exercises • Implement Book class and a client program, HuntLibrary, of the Book class •Last Class –Define a Book object –Create fields in the Book object –Create methods of the Book object –Test methods of the Book object –Create client program, HunLibrary •This Class – Book object constructor –Encapsulation of fields – Additional instance methods – Additional tests CSC116: Intro to Java Programming © Sarah Heckman 3

Book Objects (desired) //Constructor Book book1 = new Book(“title”, “author”, pubYear, location); Book book2 = new Book(); //Book with empty fields • Book Data Field Name Description title Name of the book author Author of the book pubYear Publication year of the book checkedOut Person who has checked out the book location Location of the book in the stacks dueDate Date a checked out book is due • Book Methods Method Name Description checkOut(unityId) Check out a book checkIn() Check in a book getCheckedOutTo() Person who has checked out the book getLocation() Returns the book’s location in the stacks CSC116: Intro to Java Programming © Sarah Heckman 4

2 11/2/2011

Constructing a Book Object

• Currently: Book b = new Book(); b.title = “Harry Potter”; b.author = “J. K. Rowling”; b.pubYear = 2007; b.checkedOut = “”; b.location = 7; b.dueDate = null; • Book() with no parameters –default constructor •We’ve constructed other objects (Point, Scanner, PrintStream) by passing parameters

CSC116: Intro to Java Programming © Sarah Heckman 5

Constructor

•A special method that initializes the state of new objects as they are created – Name of Constructor matches class name –No return type – Parameters that specify object’s initial state – Access object’s fields and methods directly –Can no longer use default constructor – unless explicitly define (next class) public ( , …, ) { ; … ; }

CSC116: Intro to Java Programming © Sarah Heckman 6

3 11/2/2011

Book Constructor public Book( String newTitle, String newAuthor, int newPubYear, int newLocation) { title = newTitle; author = newAuthor; pubYear = newPubYear; location = newLocation; checkedOut = “”; dueDate = null; }

CSC116: Intro to Java Programming © Sarah Heckman 7

Object Construction

Book b = new Book(“Harry Potter”, “J. K. Rowling”, 2007, 7);

1. Creates a Book reference, b 2. Creates a Book object 3. Calls Book constructor on new object passing parameters 4. Assigns the newly create object to be stored in reference variable b

CSC116: Intro to Java Programming © Sarah Heckman 8

4 11/2/2011

Update Our Client and Tests public class HuntLibrary { public static void main(String [] args) { //Create two book objects and assign title, //author, and pubYear values Book [] books = new Book[2]; books[0] = new Book("Harry Potter", "J. K. Rowling", 2007, 7); books[1] = new Book("The Lost Symbol", “Dan Brown", 2009, 8); . . .

} }

CSC116: Intro to Java Programming © Sarah Heckman 9

Encapsulation

• Hiding the implementation details of an object from the clients of the object – Protects data from unwanted access – Clients cannot directly access of modify its internal workings – nor do they need to do so –Encapsulation leads to abstraction •Want to encapsulate our Book object such that its clients can only use the objects methods and not access its data •Can later change the internal workings of the class without modifying client code

CSC116: Intro to Java Programming © Sarah Heckman 10

5 11/2/2011

Private Fields

•Private fields are visible inside the class but are not visible outside the class • Field Syntax Template private ; private = ; •Write accessor and mutator methods to access the class’s private fields – Maintain encapsulation b/c the class controls the access to internal data

CSC116: Intro to Java Programming © Sarah Heckman 11

Class Syntax Template public class { //fields private ; ... //constructors public ( ,…, ) { ; ... } ... //methods public ( ,…, ) { ; ... } ... }

CSC116: Intro to Java Programming © Sarah Heckman 12

6 11/2/2011

Class Invariants

•A property that is true of every object of a class •An assertion about an object’s state that is true for the lifetime of that object •Encapsulated objects can have constraints on their state –A Book’s title and author (almost) never changes –A Book is either checked in or checked out, which means checkedOut should never be null –Location of Book cannot be negative •Can enforce in within public methods

CSC116: Intro to Java Programming © Sarah Heckman 13

Implement a Class Invariant public Book(String newTitle, String newAuthor, int newPubYear, int newLocation) { title = newTitle; author = newAuthor; pubYear = newPubYear; setLocation(newLocation); checkedOut = “”; dueDate = null; } public void setLocation(int newLocation) { if (newLocation < 0) { throw new IllegalArgumentException(); } location = newLocation; }

CSC116: Intro to Java Programming © Sarah Heckman 14

7 11/2/2011

More Instance Methods

•There are special methods that we want to include in our classes that create instances of an object – toString – equals • Methods come from Object class and must match the syntax EXACTLY!!

CSC116: Intro to Java Programming © Sarah Heckman 15

toString •A special method that returns a String representation of an object – Called automatically by Java when concatenating and object with a String or when an object is printed –Writing your own toString method overrides the default method that prints the class name followed by @ and some letters and numbers public String toString() { return ; } CSC116: Intro to Java Programming © Sarah Heckman 16

8 11/2/2011

equals

•Method that compares two objects for equality of some or all state –Default method compares to see if objects are the same object (location or identity –same as ==) – Implemented within the class definition of the object under comparison •Compares the implicit parameter (current object) with the object passed as a parameter

CSC116: Intro to Java Programming © Sarah Heckman 17

equals Syntax Template public boolean equals(Object o) { ; ... ; return ; }

CSC116: Intro to Java Programming © Sarah Heckman 18

9 11/2/2011

Object Casting

•To compare the Object parameter to our implicit parameter, we need the Object to be an object of our class’ type • Object Casting: promise to the compiler that the Object reference actually refers to a different type and the compiler can treat it as such

Book b = (Book)o;

CSC116: Intro to Java Programming © Sarah Heckman 19

instanceof

• Passing non-Book objects will cause ClassCastExceptions • Instead, want equals method to return false if Object parameter is not a Book •Use instanceof operator to test if the Object parameter is a Book •Takes care of a null check instanceof

CSC116: Intro to Java Programming © Sarah Heckman 20

10 11/2/2011

equals Implimentation public boolean equals(Object o) { if (o instanceof Book) { Book b = (Book)o; return title.equals(b.getTitle()) && author.equals(b.getAuthor()) && pubYear == b.getPubYear(); } else { return false; } }

CSC116: Intro to Java Programming © Sarah Heckman 21

11