Вы находитесь на странице: 1из 38

SSD3: Object-Oriented Programming and

Design

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
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.
 class variables 类变量或静态变量
 Only one copy of a class variable will ever exist. That
copy is shared by all instances of the class.
 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
Sample
 Sample code (Point.java)
 Class Point models a point in the Cartesian plane .
 The class variable numberOfInstances maintains the
number of Point instances that have been created.
 Each time a Point object is created,numberOfInstances is
incremented.
 The class method getNumberOfInstances returns the class
variable numberOfInstances.
 To invoke an instance method, the method name must be
preceded by an object reference:
pointOne.setX(20);
 By convention, to invoke class method, the method name
should be preceded by the class name:
Point.getNumberOfInstances()

Object-Oriented Programme 6
note
 class variables are not part of any object so the
methods that operate on them are not associated
with any particular object.
 Class variables, if public, are also accessed using
the class name. If numberOfInstances were
declared as public, we would write:
Point.numberOfInstances
 Since class variables and class methods are not
associated with any particular object, they can be
used even when no objects of the class exist!
 we can call getNumberOfInstances before any
Point objects are created.
Object-Oriented Programme 7
Accessor and Mutator Methods 存取方法
 An accessor, or read accessor, is used to retrieve
the value of an instance variable.
 By convention, the name of an accessor is getVariableName
 VariableName is the name of the instance variable.
 A mutator, or write accessor, is used to change the
value of an instance variable.
 By convention, the name of a mutator is setVariableName.
 E.g.,
 class Point provides the accessors getX and getY and the mutators
setX and setY.

Object-Oriented Programme 8
2.1.2 Inheritance 继承
 Inheritance Implementing
 Specialization/Generalization Relationships
 Casting Objects 对象转换
 The instanceof Operator

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

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

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

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

Object-Oriented Programme 13
Casting Objects
 The reference person, which points to an Employee
object, cannot be used to invoke the Employee
methods!
 If we write
double salary = person.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 use the reference person to invoke Person
methods like getName and getAddress:
String name = person.getName(); // legal
String address = person.getAddress(); // legal

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

double salary = ((Employee) person).getSalary();

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

Object-Oriented Programme 16
The instanceof Operator
 The instanceof operator takes two operands: an object
reference and a class name.
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.
 In fact, if object is an instance of any class that has
ClassX as an ancestor, then the expression evaluates to
true.
 If the left-hand operand is null, instanceof expression
evaluates to false.
 Note
 the instanceof operator cannot be used to determine the
type of a primitive expression.

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

Object-Oriented Programme 18
2.1.3 Method equals and Method toString
 Method equals
 Method toString

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

Object-Oriented Programme 20
example
 The following code compares Point objects using the
method equals defined in class Object
Point pointOne = new Point(10, 100);
Point pointTwo = new Point(10, 100);

Point pointThree = pointOne;

if (pointOne.equals(pointTwo)) {
System.out.println("pointOne and pointTwo are equal");
} else {
System.out.println("pointOne and pointTwo are different");
}

if (pointOne.equals(pointThree)) {
System.out.println("pointOne and pointThree are equal");
} else {
System.out.println("pointOne and pointThree are different");
}

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

Object-Oriented Programme 22
Override equals()
 Equals() defined in Object is not appropriate for most
classes
 Most of class override it. 重载
 the objects being compared (return true) if they.
 have the same state,
 contain the same data,
 public boolean equals(Object object) {

if (object instanceof Point) {

Point point = (Point) object;

return point.getX() == getX() && point.getY() == getY();

} else {

return false;
}
} Object-Oriented Programme 23
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. The
reference point, unlike the reference object, can be used
to invoke the Point methods getX and getY.
 line 21
 the x and y coordinates of the two Point objects are
compared.
 Note
 this implementation applies to comparisons between
Point objects and objects of its subclasses.

Object-Oriented Programme 24
Sample code
 The following code compares Point objects using
the method equals defined in class Point. In this
example, the three Point references refer to three
different objects.
Point pointOne = new Point(10, 100);
Point pointTwo = new Point(10, 100);

Point pointThree = new Point(50, 500);

if (pointOne.equals(pointTwo)) {
System.out.println("pointOne and pointTwo are equal");
} else {
System.out.println("pointOne and pointTwo are different");
}

if (pointOne.equals(pointThree)) {
System.out.println("pointOne and pointThree are equal");
} else {
System.out.println("pointOne and pointThree are different"); 25
Object-Oriented Programme
}
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
Method toString()
 Class Object defines a method called toString that
returns the string representation of the invoking
object. 返回对象的字符串表示
 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.

Object-Oriented Programme 27
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.
/**
* Overrides {@link Object#toString()}.
* <p>
* Returns a string representation of this <code>Point</code>
* object.
* </p>
*
* @return a string representation of this <code>Point</code>
* object.
*/
public String toString() {

return "(" + getX() + "," + getY() + ")";


} Object-Oriented Programme 28
Sample
 The following code uses the method toString
defined in class Point..
Point pointOne = new Point(10, 100);
Point pointTwo = new Point(-20, 200);
Point pointThree = new Point(50, -500);

System.out.println(pointOne);
System.out.println(pointTwo);
System.out.println(pointThree);
System.out.println();

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

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

Object-Oriented Programme 31
Notes on sample
 The assertTrue() makes it easy to write test cases. It has
two input parameters: a String and a boolean. The first
argument should be an error message. This message will
be displayed if the second argument indicates a problem.
The second argument should be a test result or a test
expression, such as:
accountTwo.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;
the test cases ensure that deposit works correctly with both
valid and invalid arguments. It concludes with test cases for
withdraw that consider several possible scenarios.

Object-Oriented Programme 32
2.1.5 Implementing the Library System
 LibrarySystem Classes
 Class CatalogItem
 Class Book
 Class Recording
 Class Borrower

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

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

Object-Oriented Programme 35
Class Book
 The class Book models a book. It extends class CatalogItem.
 Instance variables:
 author.
The author of the book
 numberOfPages. The number of pages in the
book
 Constructor and methods:
 public Book(String initialCode, String initialTitle,
int initialYear, String initialAuthor, int
initialNumberOfPages) Constructor that initializes
the instance variables code, title, year, available,
author, and numberOfPages.
 public String getAuthor(). Returns the value of
instance variable author.
 public int getNumberOfPages(). Returns the
value of instance variable numberOfPages.
 String toString(). Overrides
Object-Oriented the method toString
Programme 36
Class Recording
 The class Recording models a recording, either a CD or a tape. It extends class
CatalogItem.
 Instance variables:
 performer. The performer of the recording
 format. The format of the recording
 Constructor and methods:
 public Recording(String initialCode, String
initialTitle, int initialYear, String initialPerformer,
String initialFormat) Constructor that initializes
the instance variables code, title, year, available,
performer, and format.
 public String getPerformer(). Returns the value of
instance variable performer.
 public String getFormat(). Returns the value of
instance variable format.
 String toString(). Overrides
Object-Oriented the method toString
Programme 37
Class Borrower
 The class Borrower models a user of the library.
 Instance variables:
 id. The identification number of the borrower
 name . The name of a borrower
 Constructor and methods:
 public Borrower(String initialId, String initialName) Constructor that
initializes the instance variables id and name.
 public String getId(). Returns the value of instance variable id.
 public String getName(). Returns the value of instance variable
name.
 boolean equals(Object object). Overrides the method equals in the
class Object. Two Borrower objects are equal if their identification
numbers are equal.
 String toString(). Overrides the method toString in the class Object.
Returns the string representation of the Borrower object. 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.
Object-Oriented Programme 38