Chapter 2 Slides
Download
Report
Transcript Chapter 2 Slides
Chapter 2
Polymorphism
© 2006 Pearson Education Inc., Upper Saddle River, NJ. All rights reserved.
What is Polymorphism?
●
●
●
●
Polymorphism gives us the ultimate flexibility in
extensibility.
Polymorphism is a term that describes a
situation where one name may refer to different
methods.
In java there are two types of polymorphism:
overloading type and overriding type.
Source:
http://www.programmersheaven.com/2/FAQJAVA-What-Is-Polymorphism
What is Polymorphism? (cont.)
●
●
●
Overloading occurs when several methods
have same names with different method
signature. Overloading is determined at the
compile time.
Overriding occurs when a class method has the
same name and signature as a method in
parent class.
When you override methods, java determines
the proper methods to call at the program’s run
time, not at the compile time.
Example: Overloading
Class Book {
String title, publisher;
float price;
setBook(String title) {
}
setBook(String title, String publisher) {
}
setBook(String title, String publisher, float price) {
}
}
Example: Overriding
Class Tool { // parent class
void operate_it() {
}
}
Class ScrewDriver extends Tool {
void operate_it() {
}
}
// child class
Overview
●
Polymorphism
–
●
Ability for a word or symbol to mean different things
in different contexts.
2.1 Reference (Pointer) Types
–
References
●
–
Allow for polymorphic types. That is, types of variables
which can hold more than one kind of value.
The Object type
●
●
●
●
Can hold almost anything
See slide #14
Refer to: http://download.oracle.com/javase/7/docs/api/
Then search the java.lang.Object class
Overview
●
●
●
2.2: Arrays
–
Arrays are reference types
–
Multidimensional arrays
2.3: Interfaces
–
Specify the behaviour of a class without details
of its implementation (no fields and its methods
have no bodies).
–
Interface is also a polymorphic type
2.4: Overloading
–
The ability of a method name to mean different
things depending on the types of its arguments.
Reference Types
●
Eight primitive types
–
The four commonly used:
●
●
●
●
–
boolean
char
(for example: char middleInitial = “G”;)
double
int
The other four:
●
●
●
●
byte
float
long
short
Reference Types
●
Primitive type holds its value directly.
●
All other types are reference types.
–
Including array types and object types.
–
Java sets enough memory spaces to hold the
reference, which is the address of another
location in memory.
–
When we create the array, this reference is
altered to point to the array's location.
Reference Types
●
Example: Beetle bug;
–
Java sets aside enough memory for a reference.
●
●
–
Example: bug = new Beetle();
Reference is set to point to this new instance.
If we didn't use a reference when we pass an
object as an argument to a method, we would
have to copy all of the fields into the area of
memory.
Reference Types
●
Null
–
The default value of a field with a reference type is
null.
–
Null is a reference to nothing in particular.
–
We cannot invoke a method on null.
●
–
Program will crash with an error message like:
NullPointerException
Pointer is just another word for reference.
Reference Types
●
References and Equality
–
We have rolled two dice and want to determine if
we rolled doubles.
●
What does it mean for two Die instances to be equal?
Fig. 2-1
Fig. 2-2
Reference Types
●
die1 and die2 are equal in a strong sense.
●
die2 and die3 are equal in a weaker sense.
●
The == operator checks for equality in the
strong sense.
–
die1 == die2
●
–
die2 == die3
●
–
True
False
die2.getTopFace() == die3.getTopFace()
●
True
Reference Types
●
The Polymorphic Type Object
–
A variable of type Object can hold a reference to an
instance of any class or even to an array.
–
In the example below, “it” is a polymorphic type of object.
–
Refer to: http://download.oracle.com/javase/7/docs/api/
–
Then search the java.lang.Object class
Reference Types
●
Polymorphic type
–
The Object class
●
Holds a reference to any of a wide variety of things.
–
Must be a reference type
–
Does it refer to the type of a variable or the actual
class of the instance?
●
●
These might be the same, but might not.
At compile time, Java can't tell what methods are available.
Reference Types
●
With polymorphic types, if we want to invoke a
method, we generally have to cast the value to a
specific class.
–
There are a few things we can do with an Object
without casting.
–
The getClass() method can be invoked on any Object.
●
●
It returns a representation of Object's class
Two instances of the same class return the same
representation.
Reference Types
Fig. 2-4
Reference Type
Fig. 2-5
Reference Types
●
Primitives and Wrappers
–
The Object class can hold any object or array.
●
–
It can't hold a value of a primitive type.
Java provides a wrapper class for each of the
primitive types
●
●
●
The wrapper classes are: Boolean, Byte, Character,
Double, Float, Integer, Long, and Short
The upper-case letter at the beginning of each class
name helps distinguish if from the corresponding
primitive type.
If we want to store a primitive value in a variable of type
Object, we can first wrap it in a new instance of the
appropriate class (see next slide).
Reference Types
●
Example
–
●
●
Object number = new Integer(23);
Each wrapper class has a method to
extract the original primitive value.
Example
–
intValue()
Reference Types
●
●
Java 1.5 is smart enough to handle the
following:
The tradeoff here is between generality
(writing code once to handle all sorts of
Objects) and efficiency (using the primitive
types to save time and memory).
Reference Types
●
Strings
–
●
Use equals() instead of == to compare String
objects.
Java Strings are immutable (unchangeable)
–
Their fields cannot be changed.
Reference Types
●
Java cannot always tell if two Strings are
identical.
–
s1.equals(s3)
●
–
s1 == s3
●
●
true
false
The behavior of == is difficult to predict when
Strings are involved, use equals() to compare
Strings.
Arrays
●
Declaration, Allocation, and Initialization
–
Variable must be declared and initialized.
–
There are three steps for a variable of an array
type.
●
●
●
Declaration
Allocation
Initialization
Arrays
●
The ability of a variable of an array to hold any
size is another example of polymorphism.
Arrays
●
Multidimensional Arrays
–
Array of arrays
–
Example: rows = new int[3][4]; // 3 rows & 4 columns
–
Int [][] twoDimArray = { {1,2,3}, {4,5,6}, {7,8,9}, {10,11,12} };
Fig. 2-7
Arrays
●
The above array is said to have dimensionality 2
–
●
The dimensions of the array are the number of rows
and number of columns.
Dimensionality 4
–
Example: int[][][][] tesseract = new int [2][5][4][3];
●
●
This array has dimensions 2, 5, 4, and 3.
tesseract has 120 elements (2 x 5 x 4 x 3 = 120).
Arrays
●
If we supply only one index for rows, we get a
reference to a single row of the array.
–
●
Example: int[] middleRow = rows[1];
The reference middleRow points to rows[1] only.
Fig. 2-8
Arrays
●
The following example allocates the spine
(rows --->) of the array:
int[][] rows = new int[3][];
●
Since the elements of this array are references,
they get the default value null.
Fig. 2-9
Array
●
Now we can allocate the first row with
rows[0] = new int[4];
Fig. 2-10
Arrays
●
The rows do not have to have the same length.
rows[1] = new int[2];
rows [2] = new int[3];
●
This leads to a ragged array.
Fig. 2-11
Array Example: Domineering
Array Example: Domineering (cont.)
Fig. 2-13
Array Example: Domineering (cont.)
Fig. 2-14 A single class: Domineering
Note: static methods are underlined.
Array Example: Domineering (cont.)
Fig. 2-15
Array Example: Domineering (cont.)
Fig. 2-16
Array Example: Domineering (cont.)
Fig. 2-17
Array Example: Domineering (cont.)
Fig. 2-18
Array Example: Domineering (cont.)
Fig. 2-18
Array Example: Domineering (cont.)
Fig. 2-19
Array Example: Domineering (cont.)
Fig. 2-20
Array Example: Domineering (cont.)
Fig. 2-21
Interfaces ($)
●
Interface
–
Similar to a class, except:
●
●
–
Contains no fields
Methods have no bodies
Specifies how a class behaves (what methods it
provides) without commenting on how the class is
implemented.
What is an Interface?
●
From:
http://java.sun.com/docs/books/tutorial/java/concepts/interface.html
●
●
●
●
As you've already learned, objects define their
interaction with the outside world through the methods
that they expose.
Methods form the object's interface with the outside
world;
The buttons on the front of your television set, for
example, are the interface between you and the
electrical wiring on the other side of its plastic casing.
You press the "power" button to turn the television on
and off.
What is an Interface? (cont.)
●
●
In its most common form, an interface is a group
of related methods with empty bodies (method
signature).
A bicycle's behavior, if specified as an interface,
might appear as follows:
public interface Bicycle {
void changeCadence(int newValue); // wheel revolutions per minute
void changeGear(int newValue);
void speedUp(int increment);
void applyBrakes(int decrement);
}
What is an Interface? (cont.)
●
●
To implement this interface, the name of your
class would change to a particular brand of
bicycle, for example, such as ACMEBicycle,
and you'd use the implements keyword in the
class declaration:
public class ACMEBicycle implements Bicycle {
// remainder of this class implemented as before
}
What is an Interface? (cont.)
●
●
●
Implementing an interface allows a class to become
more formal about the behavior it promises to provide.
Interfaces form a contract between the class and the
outside world, and this contract is enforced at build
time by the compiler.
If your class claims to implement an interface, all
methods defined by that interface must appear in its
source code before the class will successfully compile.
Interfaces
Fig. 2-23: interface Domino
●
A class which provides methods with these
signatures can be said to implement the
interface.
Interfaces
Fig. 2-24: FieldDomino implements Domino
Interfaces
Fig. 2-24 (cont.)
Interfaces
●
●
Leave off (no) comments for the methods
specified in the interface — javadoc will copy
them from the interface to methods.
Putting the comments in only one place
reduces the chance that inconsistent
comments will appear.
Interfaces
Fig. 2-25: ArrayDomino implements Domino
Interfaces
Fig. 2-25
Interfaces
●
●
●
It is possible for more than one class to
implement the same interface.
It is also possible for a class to implement
more than one interface.
Abstract data type or ADT
–
An interface is used to specify all of the
important methods of any implementing class
is sometimes called abstract data type.
Interface (similar to multiple inheritance)
Fig. 2-26
Interfaces
●
Many software engineers argue that a class
implementing an abstract data type should
provide only the methods, such as getLeft ()
and getRight(), required by the interface.
–
Exceptions:
●
●
●
●
Constructors
Nonpublic methods
Common methods like toString(),
main() methods for testing
Interfaces
●
If an implementation provides some other
public method, any code which takes
advantage of this method will break if we
switch to a different implementation which
does not provide it.
–
Example:
●
FieldDomino may contain a method isDoublet() to
check if both numbers on a Domino are the same.
If we call isDoublet() on a Domino which is an
instance of ArrayDomino will fail.
Overloading
●
Overloading
–
Different kind of polymorphism
–
The ability of a method to do different things
depending on the types of its arguments.
–
In Java, the + operator is overloaded.
●
●
When given numeric arguments, it performs addition.
When given Strings, it performs concatenation.
Overloading
●
It is acceptable to have two different methods
in the same class with the same name as
along as their signatures specify different
argument types.
–
Example:
●
–
playAt() could be called:
– public void play(int row, int column, boolean player)
The sequence of argument types is different from
that in the existing method.
–
–
public void play()
Java figures out which version based on the
number and types of arguments we provide.
Overloading
●
●
•
Overloading reduces the number of method
names we have to keep track of.
Without overloading, these would have the
signatures:
With overloading, we can just use one shorter name:
Summary
●
All types in Java are reference types
–
●
●
== compares if 2 references are the same
instance.
Classes often implement the equals() method to
test if 2 objects hold identical information.
–
●
Except for the 8 primitive types.
Use equals() when dealing with Strings.
Objects can contain any reference except
primitive types.
–
Wrapper classes handle primitive type references.
Summary
●
●
●
●
Arrays must be declared, allocated, and
initialized.
Multidimensional arrays are represented as
arrays of arrays.
Interfaces specify behavior without
implementing it.
Overloaded methods have several different
versions which differ in the number and
types of arguments they take.
Chapter 2 Self-Study Homework
●
Pages: 43-62
●
Exercises: 2.2, 2.10, 2.14, 2.25, 2.27