You are on page 1of 38

SSD3: Object-Oriented Programming and


Object-Oriented Programme 1

Unit 2. Class Implementation
 2.1 Implementing Classes
 2.2 Collections
 2.3 Advanced Class Design

 Assessments
 Exam 2

Object-Oriented Programme 2

2.1 Implementing Classes
 Contents
 2.1.1 Defining Classes
 2.1.2 Inheritance
 2.1.3 Method equals and Method toString
 2.1.4 Unit Testing
 2.1.5 Implementing the Library System
 Assessments
 Practical Quiz 5
 Multiple-Choice Quiz 3
 Exercise 3
Object-Oriented Programme 3

2.1.1 Defining Classes  Static Variables and Methods  Accessor and Mutator Methods Object-Oriented Programme 4 .

 A class variable is declared using the static keyword  class method 类方法或静态方法  is a method that can access only class variables.  instance method 实例方法  an instance method can access both instance and class variables.  A class method is also declared using the static keyword Object-Oriented Programme 5 . Static Variables and Methods  instance variable 实例变量  Whenever created  allocate memory for it  so each instance of the class will have its own copy of the instance variable. That copy is shared by all instances of the class.  class variables 类变量或静态变量  Only one copy of a class variable will ever exist.

numberOfInstances is incremented.  By convention.setX(20).  The class method getNumberOfInstances returns the class variable numberOfInstances.  The class variable numberOfInstances maintains the number of Point instances that have been created. Sample  Sample code (Point.  To invoke an instance  Class Point models a point in the Cartesian plane .getNumberOfInstances() Object-Oriented Programme 6 . the method name must be preceded by an object reference: pointOne. to invoke class method.  Each time a Point object is created. the method name should be preceded by the class name: Point.

If numberOfInstances were declared as public.  Class variables. we would write: Point.numberOfInstances  Since class variables and class methods are not associated with any particular object. if public. note  class variables are not part of any object so the methods that operate on them are not associated with any particular object. Object-Oriented Programme 7 . are also accessed using the class name. they can be used even when no objects of the class exist!  we can call getNumberOfInstances before any Point objects are created.

or write accessor. Accessor and Mutator Methods 存取方法  An accessor.  E.  By convention.  class Point provides the accessors getX and getY and the mutators setX and setY.  A mutator. is used to change the value of an instance variable.  By convention.. is used to retrieve the value of an instance variable. Object-Oriented Programme 8 . the name of a mutator is setVariableName.g. the name of an accessor is getVariableName  VariableName is the name of the instance variable. or read accessor.

1. 2.2 Inheritance 继承  Inheritance Implementing  Specialization/Generalization Relationships  Casting Objects 对象转换  The instanceof Operator Object-Oriented Programme 9 .

 Inheritance is a mechanism that creates a new class by "extending" or "specializing" an existing class. use the keyword extends followed by the name of the superclass: public class DerivedClass extends BaseClass { }  Object-Oriented Programme 10 .  To declare a subclass.  The new class (the subclass or child class 子类,派生类, 继承类 ) inherits the variables and methods of the existing class (the superclass or parent class 父类,基类,超类 ). Implementing Specialization/Generalization Relationships  A specialization/generalization relationship is implemented in Java using inheritance.

Sample  Sample code ( ) Object-Oriented Programme 11 .java Employee2.

 An Employee object must use the methods getName and getAddress.  The instance variables name and address are declared in Person.  In line 22. note  class Employee extends class Person. the super() call in constructors must always be the first statement. both inherited from Person. but the Employee methods cannot access these variables. to access the values of name and address.  These variables are declared private in class Person. the parent class. so the Person constructor will initialize them. the Employee constructor uses the keyword super to call the constructor in Person. so they can only be accessed by Person methods.  an instance of class Employee contains a copy of the variables name and address. Object-Oriented Programme 12 . respectively.  In Java.

0). Casting Objects  An employee is-a person.  So an Employee reference variable can be assigned to a Person reference variable. Object-Oriented Programme 13 . so every Employee object is also a Person object.  The following code creates an Employee object and assigns the Employee reference to person. "100 Main Ave". a Person reference: Person person = new Employee("Joe Smith". 3000.

// legal String address = person.getAddress(). cannot be used to invoke the Employee methods!  If we write double salary = person.getName(). Casting Objects  The reference person. // legal Object-Oriented Programme 14 .  We can use the reference person to invoke Person methods like getName and getAddress: String name = person. which points to an Employee object.getSalary(). // illegal  the compiler will complain because it can't find a method called getSalary in the class Person —  the compiler only knows the person is a Person.

we can invoke the getSalary method as follow: Employee employee = (Employee) person. Object-Oriented Programme 15 .getSalary(). // or double salary = ((Employee) person). How to do?  Java provides a work-around for the problem.  We can change the reference person into an Employee reference with a cast. double salary = employee. 类型转换  Once we have an Employee reference.getSalary().

the JVM will throw a ClassCastException because. the cast would be illegal and the Java virtual machine (JVM) would throw a ClassCastException. but when it is executed. double salary = ((Employee) person). // illegal  This code will compile. "100 Main Ave"). in this example.  If not.getSalary().  Although it is always legal to cast a subclass reference to a superclass reference. the reference person does not point to an Employee object. Object-Oriented Programme 16 . Consider the following code: 根据抽象化原理 ( 雇员是人, 但人却不都是雇员哟,还有学生,教师…… ) Person person = new Person ("Joe Smith". cast the reference  We can cast the reference person to an Employee reference because person really points to an Employee object. the reverse is not always legal.

Object-Oriented Programme 17 . object instanceof ClassX  An instanceof expression evaluates to true if the specified object is an instance of the specified class:  The expression will also evaluate to true if object is an instance of a ClassX subclass. The instanceof Operator  The instanceof operator takes two operands: an object reference and a class name.  Note  the instanceof operator cannot be used to determine the type of a primitive expression. if object is an instance of any class that has ClassX as an ancestor.  If the left-hand operand is null. instanceof expression evaluates to false. then the expression evaluates to true.  In fact.

"100 Main Ave"). if (person instanceof Employee) { salary = ((Employee) person). the cast is not made because the reference person does not point to an Employee object. }  In this example.getSalary(). Object-Oriented Programme 18 . instanceof is used to avoid an illegal cast  Sample code Person person = new Person ("Joe Smith".

3 Method equals and Method toString  Method equals  Method toString Object-Oriented Programme 19 . 2.1.

Method equals()  In Java all classes descend directly or indirectly from class Object. Object-Oriented Programme 20 .  The equals() compares two objects and returns true if and only if they are equal.  In Java a reference to an object of any type can be passed to Object reference.  so equals() can be used to compare two instances of any class.  equals() takes one input parameter . so  all classes inherit the methods defined in class Object.  equals() in class Object returns true if the objects being compared are the same object.

if (pointOne.out.out.equals(pointThree)) { System.out.println("pointOne and pointThree are different"). } else { System. } if (pointOne. example  The following code compares Point objects using the method equals defined in class Object Point pointOne = new Point(10.equals(pointTwo)) { System. Point pointThree = pointOne.println("pointOne and pointThree are equal").println("pointOne and pointTwo are equal"). Point pointTwo = new Point(10.println("pointOne and pointTwo are different"). } else { System. 100). }  Object-Oriented Programme 21 .out. 100).

another Point object is created and its reference is assigned to pointTwo. pointOne and pointTwo are compared using the default implementation of the method equals defined in class Object. pointOne and pointThree are compared.  In line 12. Note on the sample  In line 1.  In line 4. the message "PointOne and pointTwo are different" is output. pointOne is assigned to pointThree so both references refer to the same object. These references refers to the same object. so the message "PointOne and pointThree are equal" is output. Object-Oriented Programme 22 .  In line 2. Reference pointTwo refers to a different object:  In line 6. Since these references refer to different objects. a Point object is created and the reference returned from the new operator is assigned to pointOne.

 public boolean equals(Object object) { if (object instanceof Point) { Point point = (Point) object.  contain the same data. 重载  the objects being compared (return true) if they.getX() == getX() && point.getY() == getY(). } else { return false. return point. } } Object-Oriented Programme 23 . Override equals()  Equals() defined in Object is not appropriate for most classes  Most of class override it.  have the same state.

note  line 17  the instanceof operator checks if the reference object refers to a Point object.  line 19  the reference object is cast to a Point reference.  Note  this implementation applies to comparisons between Point objects and objects of its subclasses. The reference point.  line 21  the x and y coordinates of the two Point objects are compared. unlike the reference object. can be used to invoke the Point methods getX and getY. Object-Oriented Programme 24 .

Point pointTwo = new Point(10. } else { System. the three Point references refer to three different objects. Sample code  The following code compares Point objects using the method equals defined in class Point.out. 100).println("pointOne and pointTwo are equal"). Point pointThree = new Point(50. 25 Object-Oriented Programme } .equals(pointTwo)) { System. 100).out. In this example.equals(pointThree)) { System. 500). if (pointOne. } else { System.println("pointOne and pointThree are different"). } if (pointOne.out. Point pointOne = new Point(10.println("pointOne and pointTwo are different").println("pointOne and pointThree are equal").out.

note  Sample code output  References pointOne and pointTwo refer to different Point objects but these objects contain the same data so they are considered equal. Object-Oriented Programme 26 .

返回对象的字符串表示  The version of this method defined in class Object returns a String with the following format:  ClassName@number  where ClassName is the name of the object's class. and number is a hexadecimal number that identifies the object. Method toString()  Class Object defines a method called toString that returns the string representation of the invoking object. Object-Oriented Programme 27 .

" + getY() + ")". */ public String toString() { return "(" + getX() + ". * </p> * * @return a string representation of this <code>Point</code> * object. override toString()  It is recommended that all subclasses override method toString().  Classes typically redefine toString() so that the String returned contains textual representation of the object. } Object-Oriented Programme 28 . /** * Overrides {@link Object#toString()}. * <p> * Returns a string representation of this <code>Point</code> * object.

out.println(). System. Point pointThree = new Point(50.println(pointThree).  Output what? Object-Oriented Programme 29 . 100). Point pointTwo = new Point(-20.out. -500). Point pointOne = new Point(10.println(pointOne).println(pointTwo). System. Sample  The following code uses the method toString defined in class Point. System.out.out. 200).. System.

Unit testing is a technique that verifies if a class. or a new class dedicated to testing can be created. behave as expected.1. Test code can be added to the class being tested in the method main. 2. Object-Oriented Programme 30 . or a group of classes.4 Unit Testing  Unit testing is an important aspect of software design.

java  The class BankAccount contains three methods:  getBalance() to access the account balance.  deposit() to deposit money. sample   TestBankAccount. while  withdraw() will not update the balance if the account has insufficient funds.  Deposit() and withdraw() have defensive code:  deposit() will not update the balance if the specified amount is negative (or zero). Object-Oriented Programme 31 .  withdraw() to withdraw money.

It concludes with test cases for withdraw that consider several possible scenarios. The second argument should be a test result or a test expression. Object-Oriented Programme 32 . such as: accountTwo. It has two input parameters: a String and a boolean. This message will be displayed if the second argument indicates a problem. The first argument should be an error message.getBalance() == 100  main() in the test driver starts with a test case for the BankAccount constructor and the accessor getBalance(). It continues with several test cases for the method deposit. Notes on sample  The assertTrue() makes it easy to write test cases. the test cases ensure that deposit works correctly with both valid and invalid arguments.

1. 2.5 Implementing the Library System  LibrarySystem Classes  Class CatalogItem  Class Book  Class Recording  Class Borrower Object-Oriented Programme 33 .

This page describes the implementation of constructors. method equals. accessors. Object-Oriented Programme 34 . Library System Classes  The Library System tracks items checked out by borrowers. and method toString of some of the classes in the Library System. mutators.

and available.  Constructor and methods:  public CatalogItem(String initialCode. Two CatalogItem objects are equal if their codes are equal.  public boolean isAvailable(). Modifies the value of instance variable available.  public String getCode().  available.  public int getYear(). The title of the catalog item  year. The unique code that identifies the catalog item. The string returned has the following format: code_title_year_available The fields are separated by an underscore ( _ ). Returns the value of instance variable title. Overrides the method equals in the class Object. Returns the value of instance variable available.  Instance variables:  code. int initialYear) Constructor that initializes the instance variables code. The year the catalog item was published.  boolean equals(Object object).  public void setAvailable(boolean value). Returns the value of instance variable year. We assume that the fields themselves do not contain any underscores. Object-Oriented Programme 35 . title. Indicates if the catalog item is available.  public String getTitle(). Returns the value of instance variable code. Class CatalogItem  The class CatalogItem models an item in the library's catalog.  Source code (CatalogItem. Overrides the method toString in the class Object. String initialTitle. Returns the string representation of the CatalogItem object.  title.  String toString().

String initialAuthor. Returns the value of instance variable author. Class Book  The class Book models a book. int initialNumberOfPages) Constructor that initializes the instance variables code. title. Overrides Object-Oriented the method toString Programme 36 . Returns the value of instance variable numberOfPages. The author of the book  numberOfPages. String initialTitle. The number of pages in the book  Constructor and methods:  public Book(String initialCode.  Instance variables:  author.  public String getAuthor(). author. It extends class CatalogItem. and numberOfPages. int initialYear.  public int getNumberOfPages(). available.  String toString(). year.

 Instance variables:  performer. The format of the recording  Constructor and methods:  public Recording(String initialCode.  String toString(). and format. performer.  public String getPerformer(). available. Overrides Object-Oriented the method toString Programme 37 . The performer of the recording  format. title. year. Class Recording  The class Recording models a recording. It extends class CatalogItem. String initialPerformer. int initialYear. Returns the value of instance variable format.  public String getFormat(). String initialTitle. either a CD or a tape. String initialFormat) Constructor that initializes the instance variables code. Returns the value of instance variable performer.

 public String getName().  boolean equals(Object object). Returns the string representation of the Borrower object. The identification number of the borrower  name . The string representation has the following format: id_name The fields are separated by an underscore ( _ ). We assume that the fields themselves do not contain any underscores. String initialName) Constructor that initializes the instance variables id and name. Overrides the method equals in the class Object.  public String getId().  String toString(). Class Borrower  The class Borrower models a user of the library.  Instance variables:  id. Two Borrower objects are equal if their identification numbers are equal. The name of a borrower  Constructor and methods:  public Borrower(String initialId. Returns the value of instance variable name. Object-Oriented Programme 38 . Overrides the method toString in the class Object. Returns the value of instance variable id.