PPT version - University of Pittsburgh

Download Report

Transcript PPT version - University of Pittsburgh

Lec.8
(Chapter 7) Inheritance
Jiang (Jen) ZHENG
June 6th, 2005
Outline
 Inheritance
 “is a” relationship
 extends keyword
 private, public and protected
 Polymorphism
 Method overloading
 Method overriding
 Object, Method and instance variable access
 Abstract Classes
 Interfaces
 Wrappers & Casting
CS401/COE401 Summer 2005.Department of
Computer Science.University of
Pittsburgh.Lecture 8
2
Inheritance
 Sometimes we want to build a new class that
is largely like one we already have

Much of the functionality we need is already
there, but some things need to be added or
changed
 We can achieve this in object-oriented
languages using inheritance

Attributes of a base class, or superclass are
passed on to a subclass
CS401/COE401 Summer 2005.Department of
Computer Science.University of
Pittsburgh.Lecture 8
3
Inheritance and “is a”


We can understand this better by considering the “is a”
idea
 A subclass object “is a” superclass object
 However, some extra instance variables and methods
may have been added and some other methods may
have been changed
Note that “is a” is a one way operation
 Subclass “is a” superclass
 With modifications

Superclass is NOT a subclass
 Missing some properties

Ex: Button “is a” Component
CS401/COE401 Summer 2005.Department of
Computer Science.University of
Pittsburgh.Lecture 8
4
Inheritance and “is a”
Component
is a
Button


is a
is a
Label
Checkbox
Button, Label and Checkbox are all
Components
However, a Component is not necessarily a
Button, Label or Checkbox
CS401/COE401 Summer 2005.Department of
Computer Science.University of
Pittsburgh.Lecture 8
5
Extending Classes
 Inheritance in Java is implemented by
extending a class
public class NewClass extends OldClass
{
…


We then continue the definition of NewClass
as normal
However, implicit in NewClass are all data and
operations associated with OldClass

Even though we don’t see them in the definition
CS401/COE401 Summer 2005.Department of
Computer Science.University of
Pittsburgh.Lecture 8
6
private, public and protected



We already know what public and private declarations
mean
The protected declaration is between public and
private
 Protected data and methods are directly accessible in
the base class and in any subclasses
 However, they are not directly accessible anywhere
else
Note that private declarations are STILL PART of
subclasses, but they are not directly accessible from
the subclass’ point of view
 See SuperClass.java, SubClass.java and ex11.java
CS401/COE401 Summer 2005.Department of
Computer Science.University of
Pittsburgh.Lecture 8
7
Inheritance Example
 As another example


Compare MixedNumber class and
MixedNumber2 class
Both have the same functionality, but
MixedNumber uses composition and
MixedNumber2 uses inheritance

Note simplicity of MixedNumber2 methods
CS401/COE401 Summer 2005.Department of
Computer Science.University of
Pittsburgh.Lecture 8
8
Java Class Hierarchy
 In Java, class Object is the base class to all
other classes




If we do not explicitly say extends in a new
class definition, it implicitly extends Object
The tree of classes that extend from Object
and all of its subclasses are is called the class
hierarchy
All classes eventually lead back up to Object
This will enable consistent access of objects of
different classes, as we shall see shortly
CS401/COE401 Summer 2005.Department of
Computer Science.University of
Pittsburgh.Lecture 8
9
Polymorphism
 Idea of polymorphism
 See internet definition:
 On Google type “definition polymorphism” and see the
results
 This search works for many CS terms that you may be curious
about



http://www.wordiq.com/definition/Polymorphism_%28computer_science%29
Generally, it allows us to mix methods and objects of
different types in a consistent way
In Chapter 4, one type of polymorphism was already
introduced (but we did not discuss it in lecture) (see Section
4.12)
CS401/COE401 Summer 2005.Department of
Computer Science.University of
Pittsburgh.Lecture 8
10
Method Overloading

This is called ad hoc polymorphism, or method
overloading

In this case different methods within the same class or
in a common hierarchy share the same name but have
different method signatures (name + parameters +
return types)
public static float max(float a, float b)
public static float max(float a, float b, float c)
public static int max(int a, int b)

When a method is called, the call signature is matched
to the correct method version
 Note: This is done during program COMPILATION
CS401/COE401 Summer 2005.Department of
Computer Science.University of
Pittsburgh.Lecture 8
11
Method Overloading

If an exact signature match is not possible, the one
that is closest via “widening” of the values is used
 “Widening” means that values of “smaller” types are cast
into values of “larger” types
 Ex: int to long
int to float float to double
If two or more versions of the method are possible
with the same amount of “widening”, the call is
ambiguous, and a compilation error will result
See ex13.java



Note: This type of polymorphism is not necessarily
object-oriented – can be done in non-object-oriented
languages
CS401/COE401 Summer 2005.Department of
Computer Science.University of
Pittsburgh.Lecture 8
12
Polymorphism

Subclassing Polymorphism


1)
Sometimes called “true polymorphism”
Consists basically of two ideas:
Method overriding


A method defined in a superclass is redefined in
a subclass with an identical method signature
Since the signatures are identical, rather than
overloading the method, it is instead overriding
the method

For subclass objects, the definition in the subclass
replaces the version in the superclass
CS401/COE401 Summer 2005.Department of
Computer Science.University of
Pittsburgh.Lecture 8
13
Polymorphism
2)

Dynamic (or late) binding

The code executed for a method call is associated
with the call during run-time

The actual method executed is determined by the
type of the object, not the type of the reference
Allows superclass and subclass objects to be
accessed in a regular, consistent way

Array or collection of superclass references can be
used to access a mixture of superclass and subclass
objects

This is very useful if we want access collections of
mixed data types (ex: draw different graphical
objects using the same draw() method call for each)
CS401/COE401 Summer 2005.Department of
Computer Science.University of
Pittsburgh.Lecture 8
14
Polymorphism
 Ex. Each subclass
overrides the move()
method in its own way
Animal [] A = new Animal[3];
A[0] = new Bird();
A[1] = new Person();
A[2] = new Fish();
for (int i = 0; i < A.length; i++)
A[i].move();
move()
move()
• References are all the same, but objects
are not
• Method invoked is that associated with the move()
OBJECT, NOT with the
reference
CS401/COE401 Summer 2005.Department of
Computer Science.University of
Pittsburgh.Lecture 8
15
Object, Method and Instance
Variable Access
 When mixing objects of difference classes, some access
rules are important to know:


Superclass references can always be used to access
subclass objects, but NOT vice versa
Animal A = new Bird(); // this is ok
Bird B = new Animal(); // this is an ERROR
Given a reference R of class C, only methods and instance
variables that are defined (initially) in class C or ABOVE in
the class hierarchy can be accessed through R
 They still exist if defined in a subclass, but they are not
accessible through R
CS401/COE401 Summer 2005.Department of
Computer Science.University of
Pittsburgh.Lecture 8
16
Object, Method and Instance
Variable Access

Ex:

Suppose class Fish contains a new instance variable
waterType and a new method getWaterType()
Fish F = new Fish();
Animal A = new Fish();
System.out.println(F.getWaterType()); // ok
System.out.println(A.getWaterType());
 The above is NOT legal, even though the method exists
for class Fish. The reason is that the method is not
visible from the reference’s point of view (A is an Animal
reference so it can only “see” the data and methods
defined in class Animal)
System.out.println(((Fish) A).getWaterType());
 This is ok, since we have now cast the reference to the
Fish type, which CAN access the method
CS401/COE401 Summer 2005.Department of
Computer Science.University of
Pittsburgh.Lecture 8
17
Object, Method and Instance
Variable Access

Note that we can access these methods or
instance variables INDIRECTLY if an overridden
method accesses them
 So, for example, if the move() method as defined in
class Fish called the getWaterType() method, and we
called
A.move();
 It would work fine
 See ex14.java for an example
CS401/COE401 Summer 2005.Department of
Computer Science.University of
Pittsburgh.Lecture 8
18
Abstract Classes
 Abstract classes
 Sometimes in a class hierarchy, a class may be
defined simply to give cohesion to its subclasses
 No objects of that class will ever be defined
 But instance data and methods will still be inherited by
all subclasses
 This is an abstract class
 Keyword abstract used in declaration
 One or more methods declared to be abstract and are
thus not implemented
 No objects may be instantiated
CS401/COE401 Summer 2005.Department of
Computer Science.University of
Pittsburgh.Lecture 8
19
Abstract Classes


Subclasses of an abstract class must implement all
abstract methods, or they too must be declared to be
abstract
Advantages
 Can still use superclass reference to access all
subclass objects in polymorphic way
 However, we need to declare the methods we will need in
the superclass, even if they are abstract
No need to specifically define common data and
methods for each subclass - it is inherited
 Helps to organize class hierarchy
See ex15.java


CS401/COE401 Summer 2005.Department of
Computer Science.University of
Pittsburgh.Lecture 8
20
Interfaces
 Java allows only single inheritance
 A new class can be a subclass of only one
parent (super) class
 There are several reasons for this, from both the
implementation (i.e. how to do it in the compiler
and interpreter) point of view and the
programmer (i.e. how to use it effectively) point
of view
 However, it is sometimes useful to be able to
access an object through more than one
superclass reference
CS401/COE401 Summer 2005.Department of
Computer Science.University of
Pittsburgh.Lecture 8
21
Interfaces
 Interfaces allow us to do this:

A Java interface is a named set of methods





Think of it as an abstract class with no instance data
Static constants are allowed
No static methods are allowed
Any Java class (no matter what its inheritance)
can implement an interface by implementing the
methods defined in it
A given class can implement any number of
interfaces
CS401/COE401 Summer 2005.Department of
Computer Science.University of
Pittsburgh.Lecture 8
22
Interfaces

Ex:
public interface Laughable
{
public void laugh();
}
public interface Booable
{
public void boo();
}


Any Java class can implement Laughable by
implementing the method laugh()
Any Java class can implement Booable by
implementing the method boo()
CS401/COE401 Summer 2005.Department of
Computer Science.University of
Pittsburgh.Lecture 8
23
Interfaces
 Ex:
public class Comedian implements Laughable,
Booable
{
// various methods here (constructor, etc.)
public void laugh()
{
System.out.println(“Ha ha ha”);
}
public void boo()
{
System.out.println(“You stink!”);
}
CS401/COE401 Summer 2005.Department of
24
}
Computer Science.University of
Pittsburgh.Lecture 8
Interfaces



Recall our previous discussion of polymorphism
This behavior also applies to interfaces – the interface acts as a
superclass and the implementing classes implement the actual
methods however they want
An interface variable can be used to reference any object that
implements that interface


However, only the interface methods are accessible through
the interface reference
Ex:
Laughable [] funny = new Laughable[3];
funny[0] = new Comedian();
funny[1] = new SitCom(); // implements Laughable
funny[2] = new Clown(); // implements Laughable
for (int i = 0; i < funny.length; i++)
funny[i].laugh();

See ex16.java
CS401/COE401 Summer 2005.Department of
Computer Science.University of
Pittsburgh.Lecture 8
25
Wrappers
 Much useful Java functionality relies on
classes / objects



Inheritance
Polymorphic access
Interfaces
 Unfortunately, the Java primitive types are
NOT classes, and thus cannot be used in this
way

Ex: What if I want to store some collection of
mixed objects
CS401/COE401 Summer 2005.Department of
Computer Science.University of
Pittsburgh.Lecture 8
26
Wrappers

I could make an array of Object, since Object is the
superclass of all other Java classes
Object [] data = new Object[size];
However, I cannot store in here any of my primitive
types, since they are not Objects
Wrapper classes allow us to get around this problem
 Wrappers are classes that “wrap” objects around
primitive values, thus making them compatible with
other Java classes
 Each Java primitive type has a corresponding wrapper


 Ex: Integer, Float, Double, Boolean
CS401/COE401 Summer 2005.Department of
Computer Science.University of
Pittsburgh.Lecture 8
27
Wrappers


The wrapper classes also
Integer
provide extra useful
functionality for these types
 Ex: Integer.parseInt() is a
static method that enables
us to convert from a String
into an int
Double
 Ex: Character.isLetter() is
a static method that tests if
a letter is a character or
not
See more in API
CS401/COE401 Summer 2005.Department of
Computer Science.University of
Pittsburgh.Lecture 8
int
double
28
Wrappers and Casting
 Ex:
Object [] A = new Object[10];
// A[0] = 50; // This is illegal, since 50 is not
// an Object
A[0] = new Integer(50); // This is fine
A[1] = new Integer(30);


Note that an array of Object can store any Java class
(including any wrapper class)
However, because the reference is Object, we are
restricted in the methods that we can use
 Recall from our discussion of polymorphism that the
superclass reference cannot “see down” into the
subclass details
CS401/COE401 Summer 2005.Department of
Computer Science.University of
Pittsburgh.Lecture 8
29
Wrappers and Casting

Thus, if we want to access anything specific to
our wrapper class, we must first cast the
reference:
Integer i = (Integer) A[0];
Integer j = (Integer) A[1];
if (i.compareTo(j) == 0)
System.out.println(i + “ == “ + j);

We would get an error if we tried
if (A[i].compareTo(A[j]))

Also note that if we want to do any “math” with
our wrappers, we need to get the underlying
primitive values
CS401/COE401 Summer 2005.Department of
Computer Science.University of
Pittsburgh.Lecture 8
30
“Operations” with Wrappers
// Integer k = i + j; // This is illegal

The actual computation is actually quite roundabout:
Integer k = new Integer(i.intValue() +
j.intValue());
 In words: Get the primitive value of each Integer object,
add them, then create a new Integer object with the result

This leads back to the question:
 Why do we want to bother with this?
 Aren’t we better off just using int values instead of these
wrappers?

There are definite benefits to having the data
represented in a class
 Let’s see what they are
CS401/COE401 Summer 2005.Department of
Computer Science.University of
Pittsburgh.Lecture 8
31
“Generic” Operations

Let’s look at a simple example that should already be
familiar to you: Sorting
 Earlier in the term we looked at SelectionSort
 See Slides 88-89

The code was written to specifically sort ints:
static void sort(int[] data)

What if we want to sort floats, or doubles, or Strings, or
any other Java type?
 We need to write a new method for each one!!!
 The argument array must match the parameter array

Or do we??
 Can we write a single method that can sort anything?
 Discuss
CS401/COE401 Summer 2005.Department of
Computer Science.University of
Pittsburgh.Lecture 8
32
“Generic” Operations

Consider the Comparable interface:
 It contains one method:
int compareTo(Object r);
Returns a negative number if the current object is less than r,
0 if the current object equals r and a positive number if the
current object is greater than r
 Look at Comparable in the API
Consider what we need to know to sort data:
 is A[i] less than, equal to or greater than A[j]
Thus, we can sort Comparable data without knowing
anything else about it
 Awesome!
 Polymorphism allows this to work



CS401/COE401 Summer 2005.Department of
Computer Science.University of
Pittsburgh.Lecture 8
33
“Generic” Operations

Think of the objects we want to sort as “black boxes”
 We know we can compare them because they
implement Comparable
 We don’t know (or need to know) anything else about
them
 Show on board

Thus, a single sort method will work for an array of any
Comparable class
 Let’s write it now, altering the code we already know
from our simple sort method
 See Sorting.java and ex17.java
CS401/COE401 Summer 2005.Department of
Computer Science.University of
Pittsburgh.Lecture 8
34