Object-Oriented Programme 1 SSD3: Object-Oriented Programming and Design.

Презентация:



Advertisements
Похожие презентации
Inner Classes. 2 Simple Uses of Inner Classes Inner classes are classes defined within other classes The class that includes the inner class is called.
Advertisements

Unit II Constructor Cont… Destructor Default constructor.
2005 Pearson Education, Inc. All rights reserved. 1 Object-Oriented Programming: Polymorphism.
Operator Overloading Customised behaviour of operators Chapter: 08 Lecture: 26 & 27 Date:
1 © Luxoft Training 2012 Inner and anonymous classes.
1/27 Chapter 9: Template Functions And Template Classes.
1/30 Chapter 8: Dynamic Binding And Abstract classes.
2005 Pearson Education, Inc. All rights reserved. 1 Object-Oriented Programming: Interface.
© Luxoft Training 2013 Annotations. © Luxoft Training 2013 Java reflection / RTTI // given the name of a class, get a "Class" object that // has all info.
Object-Oriented Programme 1 SSD3: Object-Oriented Programming and Design.
2005 Pearson Education, Inc. All rights reserved Object-Oriented Programming: Inheritance.
A class is just a collection of variables--often of different types--combined with a set of related functions. The variables in the class are referred.
Data Types in C. A Data Type A data type is –A set of values AND –A set of operations on those values A data type is used to –Identify the type of a variable.
Object-Oriented Programme 1 SSD3: Object-Oriented Programming and Design.
Loader Design Options Linkage Editors Dynamic Linking Bootstrap Loaders.
© 2005 Cisco Systems, Inc. All rights reserved. BGP v Customer-to-Provider Connectivity with BGP Connecting a Multihomed Customer to Multiple Service.
Arrays Dr. Ramzi Saifan Slides adapted from Prof. Steven Roehrig.
HPC Pipelining Parallelism is achieved by starting to execute one instruction before the previous one is finished. The simplest kind overlaps the execution.
Initialization & Cleanup Dr. Ramzi Saifan Slides adapted from Prof. Steven Roehrig.
© Luxoft Training 2013 Java Collections API. © Luxoft Training 2013 Collections hierarchy.
Транксрипт:

Object-Oriented Programme 1 SSD3: Object-Oriented Programming and Design

Object-Oriented Programme Implementing Classes 2.2 Collections 2.3 Advanced Class Design Assessments Exam 2 Unit 2. Class Implementation

Object-Oriented Programme Implementing Classes Contents Defining Classes Inheritance Method equals and Method toString Unit Testing Implementing the Library System Assessments Practical Quiz 5 Multiple-Choice Quiz 3 Exercise 3

Object-Oriented Programme Defining Classes Static Variables and Methods Accessor and Mutator Methods

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. 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 6 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 7 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 8 Accessor and Mutator Methods 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. get set E.g., class Point provides the accessors getX and getY and the mutators setX and setY.

Object-Oriented Programme Inheritance Inheritance Inheritance Implementing Specialization/Generalization Relationships Casting Objects The instanceof Operator

Object-Oriented Programme 10 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 11 Sample Sample code (Person.java Employee2.java )

Object-Oriented Programme 12 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. In Java, the super() call in constructors must always be the first statement. super

Object-Oriented Programme 13 note private The instance variables name and address are declared in Person, so the Person constructor will initialize them. 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 14 Casting Objects Casting Objects An employee is-a person, so every Employee object is also a Person object. E.g., 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", );

Object-Oriented Programme 15 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 16 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 17 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 18 The instanceof Operator instanceof The instanceof Operator instanceof 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:

Object-Oriented Programme 19 The instanceof Operator instanceof The instanceof Operator instanceof 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 instanceof the instanceof operator cannot be used to determine the type of a primitive expression.

Object-Oriented Programme 20 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 Method equals and Method toString Method equals Method toString

Object-Oriented Programme 22 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. Object 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 23 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 24 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 25 Override equals() 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 26 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 27 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"); }

Object-Oriented Programme 28 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 29 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 is the name of the objects class, number is a hexadecimal number (16 ) that identifies the object.

Object-Oriented Programme 30 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 Object#toString()}. * * Returns a string representation of this Point * object. * a string representation of this Point * object. */ public String toString() { return "(" + getX() + "," + getY() + ")"; }

Object-Oriented Programme 31 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 Unit Testing Unit Testing Unit testing is an important aspect of software design. 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 33 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 34 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 Implementing the Library System Library System Classes Class CatalogItem Class Book Class Recording Class Borrower

Object-Oriented Programme 36 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 37 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 38 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 the method toString in the class Object. Returns the string representation of the Book object. The string returned has the following format: code_title_year_available_author_numberOfPages The fields are separated by an underscore ( _ ). We assume that the fields themselves do not contain any underscores. Source code (Book.java)

Object-Oriented Programme 39 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 the method toString in the class Object. Returns the string representation of the Recording object. The string returned has the following format: code_year_available_title_performer_format The fields are separated by an underscore ( _ ). We assume that the fields themselves do not contain any underscores. Source code(Recording.java)

Object-Oriented Programme 40 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.