CS 100Lecture 241 CS100J Lecture 24 n Previous Lecture –MatLab demonstration n This Lecture...
-
Upload
sophie-butler -
Category
Documents
-
view
215 -
download
0
Transcript of CS 100Lecture 241 CS100J Lecture 24 n Previous Lecture –MatLab demonstration n This Lecture...
CS 100 Lecture 24 1
CS100J Lecture 24CS100J Lecture 24
Previous LecturePrevious Lecture
– MatLab demonstrationMatLab demonstration
This LectureThis Lecture
– InheritanceInheritance
– Method overridingMethod overriding
– PolymorphismPolymorphism
– Reading: Reading: Lewis and Loftus, Chapter 7Lewis and Loftus, Chapter 7
Savitch, Chapter 7Savitch, Chapter 7
CS 100 Lecture 24 2
Object-Oriented ProgrammingObject-Oriented Programming
Object-oriented programming aspires to model Object-oriented programming aspires to model
the real world as a collection of the real world as a collection of objectsobjects..
Objects are classified into categories called Objects are classified into categories called
classesclasses..
Objects in the real world and in mathematics can Objects in the real world and in mathematics can
be further classified by be further classified by hierarchicalhierarchical taxonomiestaxonomies. .
For the taxonomyFor the taxonomy
we say “every Y is-a X”. For example,we say “every Y is-a X”. For example,
““every kitten is a cat”.every kitten is a cat”.
X
Y
Cat
Kitten
CS 100 Lecture 24 3
Taxonomy of PolygonsTaxonomy of Polygons
Polygon
Triangle
Isosceles
Equilateral
Rhombus
Square
Trapezoid
Parallelogram
Quadrilateral
CS 100 Lecture 24 4
Two Taxonomies of PersonTwo Taxonomies of Person
Person
boy girl
OldYoung
man woman
Person
boy man
FemaleMale
girl woman
CS 100 Lecture 24 5
Not a TaxonomyNot a Taxonomy
Person
boy man
FemaleMale
girl woman
OldYoung
Taxonomies are strictly hierarchicalTaxonomies are strictly hierarchical
CS 100 Lecture 24 6
The Class HierarchyThe Class Hierarchy
In Java, all classes are organized into a In Java, all classes are organized into a
taxonomy known as the taxonomy known as the classclass hierarchyhierarchy, Class , Class
ObjectObject is at the top of the hierarchy. is at the top of the hierarchy.
If class s is below class c in the class hierarchy, If class s is below class c in the class hierarchy,
class s is called a class s is called a subclasssubclass of c, a c is a of c, a c is a
superclasssuperclass of s. of s.
The Java class definitionThe Java class definition
classclass class-name class-name
{ . . . }{ . . . }
implicitlyimplicitly defines defines class-nameclass-name to be a subclass of to be a subclass of
class class ObjectObject..
ExampleExample. Classes . Classes AccountAccount, , RoomRoom, , PersonPerson, and , and
MatrixMatrix are each subclasses of class are each subclasses of class ObjectObject
Person
Object
Room MatrixAccount
CS 100 Lecture 24 7
Defining a SubclassDefining a Subclass
The Java class definitionThe Java class definition
classclass class-nameclass-name11 extendsextends class-name class-name22
{ . . . }{ . . . }
explicitlyexplicitly defines defines class-nameclass-name11 to be a subclass to be a subclass
of of class-nameclass-name22..
ExampleExample. .
classclass Male Male extendsextends PersonPerson
{ . . . }{ . . . }
classclass Female Female extendsextends PersonPerson
{ . . . }{ . . . }
Person
Object
Room Matrix
FemaleMale
Account
CS 100 Lecture 24 8
InheritanceInheritance
Objects of a given class have all characteristics Objects of a given class have all characteristics
(fields and methods) of objects above them in (fields and methods) of objects above them in
the hierarchy.the hierarchy.
A subclass is said to A subclass is said to inheritinherit the fields and the fields and
methods of its superclass.methods of its superclass.
The class hierarchy is sometime called the The class hierarchy is sometime called the
inheritance hierarchyinheritance hierarchy..
CS 100 Lecture 24 9
Method ResolutionMethod Resolution
Let o be an object of type Let o be an object of type tt, i.e., o was , i.e., o was
constructed by a constructor constructed by a constructor tt..
QuestionQuestion. Suppose you invoke method m on . Suppose you invoke method m on
object o. Which definition of m is invoked? object o. Which definition of m is invoked?
AnswerAnswer. The first definition of . The first definition of mm found (at run found (at run
time) in the class hierarchy, starting at time) in the class hierarchy, starting at tt, ,
working up through its superclasses, to Object.working up through its superclasses, to Object.
CS 100 Lecture 24 10
Inheritance of MethodsInheritance of Methods
classclass Room Room
{{
int id;int id; // Id number of room// Id number of room
. . .. . .
publicpublic String toString() String toString()
{ { returnreturn ”Room: ” + id; } ”Room: ” + id; }
}}
classclass Bathroom Bathroom extendsextends Room Room
{{
boolean shower; // true if room has shower.boolean shower; // true if room has shower.
. . .. . .
}}
// Client code// Client code
Room r1 = Room r1 = newnew Room(); Room();
Bathroom r2 = Bathroom r2 = newnew Bathroom(); Bathroom();
/* Room’s toString method is available for both /* Room’s toString method is available for both Rooms and Bathrooms. */Rooms and Bathrooms. */
System.out.println(r1);System.out.println(r1);
System.out.println(r2); System.out.println(r2);
CS 100 Lecture 24 11
Method OverridingMethod Overriding
Recall that if you don’t define a Recall that if you don’t define a toStringtoString
methods in a class, a “default” methods in a class, a “default” toStringtoString
method is used.method is used.
Where does that default method come from? It is Where does that default method come from? It is
the the toStringtoString method of class method of class ObjectObject..
Redefining a method that is already defined in a Redefining a method that is already defined in a
superclass is called superclass is called method overridingmethod overriding (not to be (not to be
confused with method overloading).confused with method overloading).
Method overriding lets you have a method that Method overriding lets you have a method that
is specialized for a subclass.is specialized for a subclass.
Room
Object
Bathroom
CS 100 Lecture 24 12
Field SelectionField Selection
Let e be a reference expression of type t, where Let e be a reference expression of type t, where
t is some class. i.e., at run time expression e will t is some class. i.e., at run time expression e will
evaluate to a reference to some object of type t’, evaluate to a reference to some object of type t’,
where t’ is t or a subtype of t.where t’ is t or a subtype of t.
QuestionQuestion. Suppose you select field f of whatever . Suppose you select field f of whatever
object e refers to. Which field f is accessed? object e refers to. Which field f is accessed?
AnswerAnswer. The first definition of f found (at . The first definition of f found (at
compile time) in the class hierarchy, starting at compile time) in the class hierarchy, starting at
tt, working up through its superclasses, to , working up through its superclasses, to
Object. Object.
Important point to be clarified later in the Important point to be clarified later in the
discussion about polymorphismdiscussion about polymorphism: In resolving the : In resolving the
field reference f, the search up the inheritance field reference f, the search up the inheritance
hierarchy starts at hierarchy starts at type ttype t (the type of expression (the type of expression
e), and not e), and not type t’type t’ (the type of the object). (the type of the object).
CS 100 Lecture 24 13
Inheritance of FieldsInheritance of Fields
classclass Account Account{{
int balance = 0;int balance = 0; // current balance// current balance. . .. . .
}}
classclass SavingsAccount SavingsAccount extendsextends Account Account{{
double rate = 0; double rate = 0; // interest rate// interest rate. . .. . .
}}
// Client code// Client code
Account act1 = Account act1 = newnew Account(); Account();
SavingsAccount act2 = SavingsAccount act2 = newnew SavingsAccount(); SavingsAccount();
// A SavingsAccount has both balance and rate.// A SavingsAccount has both balance and rate.
System.out.println(act2.balance); // LEGAL!System.out.println(act2.balance); // LEGAL!
System.out.println(act2.rate);System.out.println(act2.rate);
// An account has only a balance.// An account has only a balance.
System.out.println(act1.balance);System.out.println(act1.balance);
// System.out.println(act1.rate); NOT LEGAL!// System.out.println(act1.rate); NOT LEGAL!
CS 100 Lecture 24 14
Types of VariablesTypes of Variables
Recall that the type of a variable determines the Recall that the type of a variable determines the types of values that can be stored in the types of values that can be stored in the variable.variable.
A type A type t t variable can contain typevariable can contain type t t objects. objects.
Room r = Room r = newnew Room(); Room(); // LEGAL! // LEGAL!
Account act = Account act = newnew Acount(); // LEGAL! Acount(); // LEGAL!
A typeA type t t variable may not contain objects of typevariable may not contain objects of type t’t’ if if t t and and t’ t’ are unrelated types.are unrelated types.
// Room r = // Room r = newnew Account(); NOT LEGAL! Account(); NOT LEGAL!
// Account act = // Account act = newnew Room(); NOT LEGAL! Room(); NOT LEGAL!
CS 100 Lecture 24 15
PolymorphismPolymorphism
A type A type tt variable can contain any object whose variable can contain any object whose type is type is t t or a subtype of or a subtype of tt
// Client Code. // Client Code.
/* Because every Bathroom is a Room, both of the /* Because every Bathroom is a Room, both of the following statements are legal. */following statements are legal. */
Room r1 = Room r1 = newnew Room(); Room(); // LEGAL!// LEGAL!
Room r2 = Room r2 = newnew Bathroom(); Bathroom(); // LEGAL!// LEGAL!
/* You can only access fields that are guaranteed /* You can only access fields that are guaranteed to exist based on the type of the object to exist based on the type of the object reference. */reference. */
// System.out.println(r2.shower); NOT LEGAL!// System.out.println(r2.shower); NOT LEGAL!
/* Because not every Room is a Bathroom, only the /* Because not every Room is a Bathroom, only the second of the following statements is legal. second of the following statements is legal. */*/
// Bathroom r3 = // Bathroom r3 = newnew Room(); Room(); NOT LEGAL!NOT LEGAL!
Bathroom r4 = Bathroom r4 = newnew Bathroom(); Bathroom(); // LEGAL!// LEGAL!
CS 100 Lecture 24 16
Polymorphism, continuedPolymorphism, continued
classclass Room Room
{{
int id;int id; // Id number of room// Id number of room
. . .. . .
publicpublic String toString() String toString()
{ { returnreturn ”Room: ” + id; } ”Room: ” + id; }
}}
classclass Bathroom Bathroom extendsextends Room Room
{{
. . .. . .
publicpublic String toString() String toString()
{ { returnreturn ”Bathroom: ” + id; } ”Bathroom: ” + id; }
}}
/* Client code. The class of the object, not the /* Client code. The class of the object, not the type of the variable, determines which method type of the variable, determines which method is invoked. */is invoked. */
Room r1 = Room r1 = newnew Room(); Room();
System.out.println(r1); // output: “Room: …”System.out.println(r1); // output: “Room: …”
Room r2 = Room r2 = newnew Bathroom(); Bathroom();
System.out.println(r2); // output: “Bathroom: …”System.out.println(r2); // output: “Bathroom: …”