inheritance, polymorphism, class hierarchies and generics

70
INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

Upload: blaise-lawrence

Post on 28-Dec-2015

250 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

Page 2: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

2

Introduction to Inheritance and Class Hierarchies

Popularity of OOP is that it enables programmers to reuse previously written code saved as classes

All Java classes are arranged in a hierarchy, starting with Object, which is the superclass of all Java classes

Inheritance in OOP is analogous to inheritance in humans

Inheritance and hierarchical organization allow you to capture the idea that one thing may be a refinement or extension of another

Page 3: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

3

Introduction to Inheritance and Class Hierarchies (continued)

Page 4: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

4

Is-a Versus Has-a Relationships One misuse of inheritance is confusing

the has-a relationship with the is-a relationship

The has-a relationship means that one class has the second class as an attribute

We can combine is-a and has-a relationships

The keyword extends specifies that one class is a subclass of another

Page 5: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

5

A Superclass and a Subclass

Consider two classes: Computer and Laptop

A laptop is a kind of computer and is therefore a subclass of computer

Page 6: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

6

Initializing Data Fields in a Subclass and the No-Parameter Constructor

Private data fields belonging to a base class must be initialized by invoking the base class’s constructor with the appropriate parameters

If the execution of any constructor in a subclass does not invoke a superclass constructor, Java automatically invokes the no-parameter constructor for the superclass Initializes that part of the object inherited from

the superclass before the subclass starts to initialize its part of the object

Page 7: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

7

Protected Visibility for Superclass Data Fields

Private data fields are not accessible to derived classes

Protected visibility allows data fields to be accessed either by the class defining it or any subclass

In general, it is better to use private visibility because subclasses may be written by different programmers and it is always good practice to restrict and control access to the superclass data fields

Page 8: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

8

Method Overriding

If a derived class has a method found within its base class, that method will override the base class’s method

The keyword super can be used to gain access to superclass methods overridden by the base class

A subclass method must have the same return type as the corresponding superclass method

Page 9: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

9

Method Overloading

Method overloading: having multiple methods with the same name but different signatures in a class

Constructors are often overloaded Example:

MyClass(int inputA, int inputB) MyClass(float inputA, float inputB)

Page 10: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

10

Polymorphism

A variable of a superclass type can reference an object of a subclass type

Polymorphism means many forms or many shapes

Polymorphism allows the JVM to determine which method to invoke at run time

At compile time, the Java compiler can’t determine what type of object a superclass may reference but it is known at run time

Page 11: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

11

Abstract Classes, Assignment, and Casting in a Hierarchy

An interface can declare methods but does not provide an implementation of those methods Methods declared in an interface are called

abstract methods An abstract class can have abstract methods,

data fields, and concrete methods Abstract class differs from a concrete class in

that An abstract class cannot be instantiated An abstract class can declare abstract methods,

which must be implemented in its subclasses

Page 12: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

12

Abstract Classes and Interfaces Like an interface, an abstract class can’t

be instantiated An abstract class can have constructors

to initialize its data fields when a new subclass is created Subclass uses super(…) to call the

constructor May implement an interface but it

doesn’t have to define all of the methods declared in the interface Implementation is left to its subclasses

Page 13: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

13

Abstract Class Number and the Java Wrapper Classes

Page 14: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

14

Summary of Features of Actual Classes, Abstract Classes, and Interfaces

Page 15: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

15

Class Object, Casting and Cloning Object is the root of the class hierarchy;

every class has Object as a superclass All classes inherit the methods defined in

class Object but may be overridden

Page 16: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

16

The Method toString

You should always override the toString method if you want to represent an object’s state

If you do not override it, the toString method for class Object will return a string…just not the string you want or are expecting

Page 17: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

17

Operations Determined by Type of Reference Variable

A variable can reference an object whose type is a subclass of the variable type

The type of reference, not the type of the object referenced, determines what operations can be performed

Java is a strongly typed language so the compiler always verifies that the type of the expression being assigned is compatible with the variable type

Page 18: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

18

Casting in a Class Hierarchy

Java provides casting to enable us to process one object referenced by one type through a reference variable of its actual type

Casting does not change the object referenced; it creates an anonymous reference to that object

Downcast: cast a higher type to a lower type The instanceof operator can guard against

ClassCastException errors You can downcast an interface reference to the

specific implementation type

Page 19: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

19

The Method Object.equals

The Object.equals method has a parameter of type Object

Compares two objects to determine whether they are equal

You must override the equals method if you want to be able to compare two objects of a class

Page 20: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

20

Cloning

The purpose of cloning in object-oriented programming is analogous to cloning in biology Create an independent copy of an object

Initially, both objects will store the same information

You can change one object without affecting the other

Page 21: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

21

The Shallow Copy Problem

Page 22: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

22

The Object.clone method

Java provides the Object.clone method to help solve the shallow copy problem

The initial copy is a shallow copy as the current object’s data fields are copied

To make a deep copy, you must create cloned copies of all components by invoking their respective clone methods

Page 23: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

23

Multiple Inheritance, Multiple Interfaces, and Delegation

Multiple inheritance: the ability to extend more than one class

Multiple inheritance is a language feature that is difficult to implement and can lead to ambiguity Therefore, Java does not allow a class to

extend more than one class

Page 24: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

24

Using Multiple Interfaces to Emulate Multiple Inheritance

If we define two interfaces, a class can implement both

Multiple interfaces emulate multiple inheritance

Page 25: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

25

Implementing Reuse Through Delegation

You can reduce duplication of modifications and reduce problems associated with version control through a technique known as delegation

In delegation, a method of one class accomplishes an operation by delegating it to a method of another class

Page 26: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

Chapter 3: Inheritance and Class Hierarchies

26

Packages

The Java API is organized into packages The package to which a class belongs is declared

by the first statement in the file in which the class is defined using the keyword package followed by the package name

All classes in the same package are stored in the same directory or folder

All the classes in one folder must declare themselves to be in the same package

Classes that are not part of a package may access only public members of classes in the package

Page 27: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

Chapter 3: Inheritance and Class Hierarchies

27

The No-Package-Declared Environment and Package Visibility

There exists a default package Files that do specify a package are considered part

of the default package If you don’t declare packages, all of your

packages belong to the same, default package Package visibility sits between private and

protected Classes, data fields, and methods with package visibility

are accessible to all other methods of the same package but are not accessible to methods outside of the package

Classes, data fields, and methods that are declared protected are visible to all members of the package

Page 28: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

28

Visibility Supports Encapsulation The rules for visibility control how

encapsulation occurs in a Java program Private visibility is for members of a class that

should not be accessible to anyone but the class, not even the classes that extend it

Package visibility allows the developer of a library to shield classes and class members from classes outside the package

Use of protected visibility allows the package developer to give control to other programmers who want to extend classes in the package

Page 29: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

29

Visibility Supports Encapsulation (continued)

Page 30: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

30

A Shape Class Hierarchy

Page 31: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

31

A Shape Class Hierarchy (continued)

Page 32: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

32

A Shape Class Hierarchy (continued)

Page 33: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

Introduction

Generics New feature of J2SE 5.0 Provide compile-time type safety

Catch invalid types at compile time Generic methods

A single method declaration A set of related methods

Generic classes A single class declaration A set of related clases

Page 34: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

Motivation for Generic Methods

Overloaded methods Perform similar operations on different

types of data Overloaded printArray methods

Integer array Double array Character array

Only reference types can be used with generic methods and classes

Page 35: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

Motivation for Generic Methods (Cont.)

Study each printArray method Array element type appears in two location

Method header for statement

Combine three printArray methods into one

Replace the element types with a generic name E

Declare one printArray method Display the string representation of the

elements of any array

Page 36: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

Generic Methods: Implementation and Compile-Time Translation

Generic method declaration Type parameter section

Delimited by angle brackets ( < and > ) Precede the method’s return type Contain one or more type parameters

Also called formal type paramters

Page 37: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

Generic Methods: Implementation and Compile-Time Translation

Type parameter (Also known as type variable) An identifier that specifies a generic type name Used to declare return type, parameter types and local

variable types Act as placeholders for the types of the argument passed

to the generic method Actual type arguments

Can be declared only once but can appear more than once

public static < E > void printTwoArrays( E[] array1, E[] array2 )

Page 38: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

Generic Methods: Implementation and Compile-Time Translation (Cont.)

Compile-time translation Erasure

Remove type parameter section Replace type parameters with actual types Default type is Object

Page 39: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

Additional Compile-Time Translation Issues: Methods That Use a Type Parameter as the Return Type

Application of Fig. 18.5 Generic method Use Type parameters in the return type and

parameter list Generic interface

Specify, with a single interface declaration, a set of related types

E.g., Comparable< T > Method integer1.compareTo( integer2 )

Compare two objects of the same class Return 0 if two objects are equal Return -1 if integer1 is less than integer2 Return 1 if integer1 is greater than integer2

Page 40: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

Additional Compile-Time Translation Issues: Methods That Use a Type Parameter as the Return Type (Cont.)

Upper bound of type parameter Default is Object Always use keyword extends

E.g., T extends Comparable< T > When compiler translates generic method to

Java bytecode Replaces type parameter with its upper bound Insert explicit cast operatione.g., line 23 of Fig. 18.5 I preceded by an Integer

cast(Integer) maximum( 3, 4, 5 )

Page 41: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

Overloading Generic Method Generic method may be overloaded

By another generic method Same method name but different method

parameters By non-generic methods

Same method name and number of parameters When compiler encounters a method call

Search for most precise matching method first Exact method name and argument types

Then search for inexact but applicable matching method

Page 42: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

Generic Classes

Generic classes Use a simple, concise notation to indicate

the actual type(s) At compilation time, Java compiler

ensures the type safety uses the erasure technique to enable client

code to interact with the generic class Parameterized classes

Also called parameterized types E.g., Stack< Double >

Page 43: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

Generic Classes (Cont.)

Generic class declaration Looks like a non-generic class declaration Except class name is followed by a type

parameter section The –Xlint:unchecked option

Compiler cannot 100% ensure type safety

Page 44: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

Generic Classes (Cont.)

Generic class at compilation time Compiler performs erasure on class’s type

parameters Compiler replaces type parameters with

their upper bound Generic class test program at

compilation time Compiler performs type checking Compiler inserts cast operations as

necessary

Page 45: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

Generic Classes (Cont.)

Creating generic methods to test class Stack< E > Method testPush

Perform same tasks as testPushDouble and testPushInteger

Method testPop Perform same tasks as testPopDouble and testPopInteger

Page 46: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

Wildcards in Methods That Accept Type Parameters

Data structure ArrayList Dynamically resizable, array-like data

structure Method add Method toString

Page 47: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

Wildcards in Methods That Accept Type Parameters

Motivation for using wildcards Implement a generic method sum

Total the numbers in a collection Receive a parameter of type ArrayList< Number >

Use method doubleValue of class Number to obtain the Number’s underlying primitive value as a double value

Page 48: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

Wildcards in Methods That Accept Type Parameters (Cont.)

Implementing method sum with a wildcard type argument in its parameter Number is the superclass of Integer ArrayList< Number > is not a supertype of ArrayList< Integer >

Cannot pass ArrayList< Integer > to method sum

Page 49: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

Generics and Inheritance: Notes Inheritance in generics

Generic class can be derived from non-generic class

e.g., class Object is superclass of every generic class Generic class can be derived from another generic class

e.g., Stack is a subclass of Vector Non-generic class can be derived from generic class

e.g., Properties is a subclass of Hashtable Generic method in subclass can override generic method

in superclass If both methods have the same signature

Page 50: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

COLLECTIONS

Page 51: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

Introduction

Java collections framework Contain prepackaged data structures,

interfaces, algorithms Use generics Use existing data structures

Example of code reuse Provides reusable components

Page 52: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

Collections Overview

Collection Data structure (object) that can hold

references to other objects Collections framework

Interfaces declare operations for various collection types

Provide high-performance, high-quality implementations of common data structures

Enable software reuse

Page 53: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

Some collection framework interfaces.

Interface Description

Collection The root interface in the collections hierarchy from which interfaces Set, Queue and List are derived.

Set A collection that does not contain duplicates. List An ordered collection that can contain duplicate elements. Map Associates keys to values and cannot contain duplicate keys. Queue Typically a first-in, first-out collection that models a waiting line; other

orders can be specified.

Page 54: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

Class Arrays

Class Arrays Provides static methods for manipulating

arrays Provides “high-level” methods

Method binarySearch for searching sorted arrays

Method equals for comparing arrays Method fill for placing values into arrays Method sort for sorting arrays

Page 55: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

Interface Collection and Class Collections

Interface Collection Root interface in the collection hierarchy Interfaces Set, Queue, List extend interface Collection

Set – collection does not contain duplicates Queue – collection represents a waiting line List – ordered collection can contain duplicate elements

Contains bulk operations Adding, clearing, comparing and retaining objects

Provide method to return an Iterator object Walk through collection and remove elements from collection

Page 56: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

Interface Collection and Class Collections (Cont.)

Class Collections Provides static methods that manipulate

collections Implement algorithms for searching, sorting

and so on Collections can be manipulated

polymorphically Synchronized collection Unmodifiable collection

Page 57: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

Software Engineering Observation

The collections framework algorithms are polymorphic. That is, each algorithm can operate on objects that implement specific interfaces, regardless of the underlying implementations.

Page 58: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

Lists

List Ordered Collection that can contain

duplicate elements Sometimes called a sequence Implemented via interface List

ArrayListLinkedListVector

Page 59: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

Performance Tip

ArrayLists behave like Vectors without synchronization and therefore execute faster than Vectors because ArrayLists do not have the overhead of thread synchronization.

Page 60: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

Software Engineering Observation

LinkedLists can be used to create stacks, queues, trees and dequeus (double-ended queues, pronounced “decks”). The collections framework provides implementations of some of these data structures.

Page 61: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

ArrayList and Iterator

ArrayList example Demonstrate Collection interface

capabilities Place two String arrays in ArrayLists Use Iterator to remove elements in ArrayList

Page 62: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

LinkedList

LinkedList example Add elements of one List to the other Convert Strings to uppercase Delete a range of elements

Page 63: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

Linkedlist (Cont.)

static method asList of class Arrays View an array as a List collection Allow programmer to manipulate the array

as if it were a list Any modification made through the List

view change the array Any modification made to the array change

the List view Only operation permitted on the view

returned by asList is set

Page 64: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

Vector

Class Vector Array-like data structures that can resize

themselves dynamically Contains a capacity Grows by capacity increment if it requires

additional space

Page 65: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

Performance Tip

Inserting an element into a Vector whose current size is less than its capacity is a relatively fast operation.

Inserting an element into a Vector that needs to grow larger to accommodate the new element is a relatively slow operation.

Page 66: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

Collections Algorithms

Collections framework provides set of algorithms Implemented as static methods

List algorithms sort binarySearch reverse shuffle fill copy

Page 67: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

Collections Algorithms

Collection algorithms min max addAll frequency disjoint

Page 68: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

Collections algorithms.

Algorithm Description

sort Sorts the elements of a List.

binarySearch Locates an object in a List.

reverse Reverses the elements of a List.

shuffle Randomly orders a List’s elements.

fill Sets every List element to refer to a specified object.

Copy Copies references from one List into another.

min Returns the smallest element in a Collection.

max Returns the largest element in a Collection.

addAll Appends all elements in an array to a collection.

frequency Calculates how many elements in the collection are equal to the specified element.

disjoint Determines whether two collections have no elements in common.

Page 69: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

Algorithm sort

sort Sorts List elements

Order is determined by natural order of elements’ type List elements must implement the Comparable interface Or, pass a Comparator to method sort

Sorting in ascending order Collections method sort

Sorting in descending order Collections static method reverseOrder

Sorting with a Comparator Create a custom Comparator class

Page 70: INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS

Algorithm binarySearch

binarySearch Locates object in List

Returns index of object in List if object exists Returns negative value if Object does not exist

Calculate insertion point Make the insertion point sign negative Subtract 1 from insertion point