49
CS 106 Introduction to Computer Science I 11 / 27 / 2006 Instructor: Michael Eckmann

CS 106 Introduction to Computer Science I 11 / 27 / 2006 Instructor: Michael Eckmann

Embed Size (px)

Citation preview

Page 1: CS 106 Introduction to Computer Science I 11 / 27 / 2006 Instructor: Michael Eckmann

CS 106Introduction to Computer Science I

11 / 27 / 2006

Instructor: Michael Eckmann

Page 2: CS 106 Introduction to Computer Science I 11 / 27 / 2006 Instructor: Michael Eckmann

Michael Eckmann - Skidmore College - CS 106 - Fall 2006

Today’s Topics• Comments and/or Questions?• Polymorphism (via Inheritance)• review of concepts from last class

– abstract class / abstract method

– overriding abstract methods / non-abstract methods

• Interfaces

– polymorphism via interfaces

– Comparable

– example usage in Card

– sorting using Comparables

• ArrayList class

Page 3: CS 106 Introduction to Computer Science I 11 / 27 / 2006 Instructor: Michael Eckmann

Polymorphism• Polymorphism --- having many forms

• A polymorphic reference variable is one that can refer to different types of objects at different points in time

• An example from a text I used in the past (Lewis and Loftus):

obj.doIt();

• If obj is polymorphic --- meaning it can take on the value of different types of objects throughout the running of the program then it might be calling different versions of the doIt() method.

• What does that mean --- different versions of the doIt() method?

Page 4: CS 106 Introduction to Computer Science I 11 / 27 / 2006 Instructor: Michael Eckmann

Polymorphism• It means doIt() may be a method that is in multiple classes and

the actual method that gets executed depends on the type of the object.

• You can imagine that line of code:

obj.doIt();

may be in a loop. Then, if the obj reference changes and actually refers to different types of objects, the different versions of doIt() are called.

• This deals with the concept of binding.

Page 5: CS 106 Introduction to Computer Science I 11 / 27 / 2006 Instructor: Michael Eckmann

Binding• Binding of a variable to a type usually occurs at compile-time. This

means that when Java compiles the source code, it can figure out the exact type (class) associated with each variable name in the code at the time the code is compiled.

• In the case of polymorphism, this binding of a variable to a type can only be done at runtime. Why?

• This is called late binding or dynamic binding. Java needs to determine the ACTUAL type of the object being referred to by the reference.

Pet p;

// some code here to assign an object to p

p.speak();

Page 6: CS 106 Introduction to Computer Science I 11 / 27 / 2006 Instructor: Michael Eckmann

Polymorphism via Inheriance• It can go futher. If Pet inherits from LivingThing, then

this is allowed:

LivingThing lt;

Pet a_pet;

Dog d = new Dog(“Max”);

a_pet = d;

lt = d;

• Here, the Dog reference is being stored in a reference (a_pet) of its immediate superclass (Pet) and also stored in a reference (lt) of a higher superclass (LivingThing.)

Page 7: CS 106 Introduction to Computer Science I 11 / 27 / 2006 Instructor: Michael Eckmann

Polymorphism via Inheriance• Below, some_pet is polymorphic because it can refer to a

Dog object or a Cat object (or a Pet object if Pet is instantiable --- that is, not abstract.)

Pet some_pet = new Dog(“Max”);

System.out.println(some_pet.makeNoise());

// Because there are subclasses of Pet (namely Dog

// and Cat) the some_pet reference can refer to different

// types of objects -> Java must know which makeNoise()

// method to execute (the one in Dog, Cat or Pet)

Page 8: CS 106 Introduction to Computer Science I 11 / 27 / 2006 Instructor: Michael Eckmann

Polymorphism via InheriancePet some_pet = new Dog(“Max”);

some_pet = new Cat(“Kitty”);

System.out.println(pet.makeNoise());

That's where the dynamic binding of variable to actual type comes into play.

Above, some_pet was a reference to a Dog then it became a reference to a Cat, so the makeNoise() method is the Cat's makeNoise method that it executes.

Page 9: CS 106 Introduction to Computer Science I 11 / 27 / 2006 Instructor: Michael Eckmann

Polymorphism via InherianceWe saw our Dog, Cat, TalkingDog and Pet classes from

last time used polymorphic references.

Page 10: CS 106 Introduction to Computer Science I 11 / 27 / 2006 Instructor: Michael Eckmann

Overriding methods• Polymorphism is possible via inheritance because of

overriding methods.

• A subclass can override a superclass's method by providing a definition for a method that exists in the superclass with the same name and number and type of parameters.

• A class containing an abstract method is not instantiable (can't create objects of this class) instead it is used as a superclass.

– If a subclass wants to be instantiable then the subclass that derives from the abstract superclass is required to implement (provide code for) any abstract methods in the superclass.

Page 11: CS 106 Introduction to Computer Science I 11 / 27 / 2006 Instructor: Michael Eckmann

Overriding methods• speak() was an abstract method in the parent class Pet.• All subclasses of Pet were required to implement that method if the

subclasses were to be instantiable.• If speak() did not live in Pet, then we would still be allowed to

have speak() methods in all the subclasses but we would lose a couple of benefits:

– 1) nothing requires the signatures of the speak() methods in each subclass to be the same.

– 2) we won't be able to call the speak() method using a reference to a Pet.

• Being able to call the speak() method on a reference to a Pet --- that's the key concept here. Only during runtime does Java know what kind of object is referenced by a Pet reference

Page 12: CS 106 Introduction to Computer Science I 11 / 27 / 2006 Instructor: Michael Eckmann

Polymorphism• Being able to call the speak() method on a reference to a Pet ---

that's the key concept here.

• Only during runtime, during the time that the actual method call occurs does Java know what kind of object is referenced by a Pet reference. A Pet reference could refer to a Dog, Cat or TalkingDog object (because these classes all derive from Pet directly or indirectly.)

• Java then calls the appropriate speak() method based on which kind of object is actually calling speak() (i.e. a Dog, Cat or TalkingDog).

Page 13: CS 106 Introduction to Computer Science I 11 / 27 / 2006 Instructor: Michael Eckmann

abstract methods• The reason we create an abstract method (with an empty method body)

in the superclass is so that this guarantees that all subclasses must provide this method if they are to be instantiable.

• Make the method abstract if the superclass doesn't need to be instantiable and if there is no obvious default behavior for the method in the superclass --- this passes the requirement of the behavior of the abstract method to any subclass that wants to be instantiable.

• Notice:

– a subclass of Pet had to include code for the speak() method

– we couldn't instantiate an object of type Pet because it is abstract

Page 14: CS 106 Introduction to Computer Science I 11 / 27 / 2006 Instructor: Michael Eckmann

Interfaces• An interface is a collection of constants and abstract methods.

–What are constants? What are abstract methods?

• An interface can never be instantiated. What does that mean again?

• The purpose of interfaces are to formally define the ways in which we can interact with a class (that implements the interface).

Page 15: CS 106 Introduction to Computer Science I 11 / 27 / 2006 Instructor: Michael Eckmann

Interfaces• We can create our own interfaces.

• We can also use interfaces in the Java API.

• Let's see code examples with our own interfaces first.

Page 16: CS 106 Introduction to Computer Science I 11 / 27 / 2006 Instructor: Michael Eckmann

Polymorphism via Interfaces• Just as we could create references to parent classes

(even if they were abstract), we can create references to interfaces.

• But these references are not instantiable. Why not?

• Example code:public interface Speaker

{

public void speak();

public void announce(String str);

} // here the abstract keyword is implied on these methods

Page 17: CS 106 Introduction to Computer Science I 11 / 27 / 2006 Instructor: Michael Eckmann

Polymorphism via Interfacespublic class Philosopher implements Speaker

{ // partial class definition ...

public void speak()

{

System.out.println(“I am a philosopher...”);

}

public void announce(String str)

{

System.out.println(“My announcement is ” + str);

}

public void pontificate()

{

System.out.println(“Do as I say, not as I do.”);

}

}

Page 18: CS 106 Introduction to Computer Science I 11 / 27 / 2006 Instructor: Michael Eckmann

Polymorphism via Interfacespublic class AttorneyGeneral implements Speaker

{ // partial class definition ...

public void speak()

{

System.out.println(“I am the Attorney General”);

}

public void announce(String str)

{

System.out.println(“My announcement is ” + str);

}

}

Page 19: CS 106 Introduction to Computer Science I 11 / 27 / 2006 Instructor: Michael Eckmann

Polymorphism via Interfacespublic class Dog implements Speaker

{

// partial class definition ...

public void speak()

{

System.out.println(“woof”);

}

public void announce(String str)

{

System.out.println(“woof woof ” + str + “ woof woof”);

}

}

Page 20: CS 106 Introduction to Computer Science I 11 / 27 / 2006 Instructor: Michael Eckmann

Polymorphism via Interfaces• In some method of some class we could have:

Speaker lecturer;

lecturer = new Philosopher();

lecturer.speak(); // call's Philosopher's speak method

lecturer = new Dog();

lecturer.speak(); // call's Dog's speak method

lecturer = new AttorneyGeneral();

lecturer.speak(); // call's Attorney General's speak method

• We can do this because lecturer is a reference to a Speaker. This means that it can reference any object of a class that implements Speaker.

• First it references a Philosopher object, then later it references a Dog object, then later an Attorney General object.

Page 21: CS 106 Introduction to Computer Science I 11 / 27 / 2006 Instructor: Michael Eckmann

Polymorphism via InterfacesSpeaker lecturer;

lecturer = new Philosopher();

lecturer.pontificate(); // error here

• Because lecturer is a Speaker reference, only the methods that are defined in Speaker can be called the way we did on the previous slide.

• We (as the programmer) know though, that lecturer references a Philosopher object (which can call the pontificate method.) So, we can cast the reference to a Philosopher to be able to call a method that is not part of all Speakers via a reference to a Speaker.

• ((Philosopher) lecturer).pontificate();

Page 22: CS 106 Introduction to Computer Science I 11 / 27 / 2006 Instructor: Michael Eckmann

Polymorphism via Interfacespublic void on_lecture_circuit (Speaker sp)

{sp.speak();sp.announce(“They have computers, and they may have

other weapons of mass destruction.”);

}

• Interface references can be used as parameters too (just like polymorphic references based on inheritance.)

• So, here, we can pass into the on_lecture_circuit method, any object of any class that implements Speaker.

AttornerGeneral reno = new AttorneyGeneral();

on_lecture_circuit (reno);

Page 23: CS 106 Introduction to Computer Science I 11 / 27 / 2006 Instructor: Michael Eckmann

Interfaces• There are many interfaces in the Java API available for us to

use.

• One of these is the interface Comparable

• It contains one abstract method:

– int compareTo( object_to_be_compared )

– It returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object. Negative means <, Positive means > and 0 means equal.

• It is up to a class that implements the Comparable interface to determine what it means for its objects to be <, > or = to each other. That is specified in the implementation of the method.

Page 24: CS 106 Introduction to Computer Science I 11 / 27 / 2006 Instructor: Michael Eckmann

Interfaces• Example use of Comparable

• int compareTo( object_to_be_compared )

• Let's edit our Card class to implement Comparable.

• Will we have to add a compareTo method?

Page 25: CS 106 Introduction to Computer Science I 11 / 27 / 2006 Instructor: Michael Eckmann

Interfaces• Example use of Comparable

• int compareTo( object_to_be_compared )

• Let's edit our Card class to implement Comparable.

• Will we have to add a compareTo method?

–Yes! If the class implements Comparable it must provide implementation of ALL the abstract methods of the interface.

• What might our compareTo method do in the Card class?

Page 26: CS 106 Introduction to Computer Science I 11 / 27 / 2006 Instructor: Michael Eckmann

Interfaces• int compareTo( object_to_be_compared )

• Let's edit our Card class to implement Comparable.

• Will we have to add a compareTo method?

–Yes! If the class implements Comparable it must provide implementation of ALL the abstract methods of the interface.

• What might our compareTo method do in the Card class?

– It should return a negative # if the “calling” Card object is less than the Card object that is passed in as a parameter.

– It should return 0 if the Card objects are equal

–Otherwise return a positive number.

Page 27: CS 106 Introduction to Computer Science I 11 / 27 / 2006 Instructor: Michael Eckmann

Interfaces• The Card class has rank and suit as instance variables.

• Our compareTo method will look like:

public int compareTo(Object o)

{

// how do we refer to the values

// associated with the “calling” Card object?

// how do we refer to the values

// associated with the parameter object?

}

Page 28: CS 106 Introduction to Computer Science I 11 / 27 / 2006 Instructor: Michael Eckmann

Interfaces• Let's take a look at the String class in the Java API

documentation online.

• Recall using compareTo with Strings.

• String class implements Comparable.

Page 29: CS 106 Introduction to Computer Science I 11 / 27 / 2006 Instructor: Michael Eckmann

Interfaces• Let's say we wanted to sort an array of Cards.

– Since Deck has an array of cards why don't we have a way to put the Cards back in order after shuffling.

• Let's create a helper class that contains a sorting method that generally sorts Comparables

– We can base the sort method on the bubbleSort method we have that sorts an array of ints.

• but we would like it to sort an array of Comparables!• Let's look at code for the original bubbleSort method to

sort an array of ints.

Page 30: CS 106 Introduction to Computer Science I 11 / 27 / 2006 Instructor: Michael Eckmann

Using Comparable• Original bubbleSort was:

public void bubbleSort( int array2[] )

{

for ( int pass = 1; pass < array2.length; pass++ )

{

for ( int element = 0; element < (array2.length - 1); element++ )

{

if ( array2[ element ] > array2[ element + 1 ] )

{

swap( array2, element, element + 1 );

} // end if

} // end inner for loop (element)

} // end outer for loop (pass)

} // end method bubbleSort

Page 31: CS 106 Introduction to Computer Science I 11 / 27 / 2006 Instructor: Michael Eckmann

Using Comparable• Original swap was:

public void swap( int array3[], int first, int second )

{

int hold;

hold = array3[ first ];

array3[ first ] = array3[ second ];

array3[ second ] = hold;

}

Page 32: CS 106 Introduction to Computer Science I 11 / 27 / 2006 Instructor: Michael Eckmann

Interfaces• In the next lab you'll create a class that implements

Comparable.

– A class to store contact information for someone. You'll store a person's first name, last name, and phone number.

– You'll create an array of Contacts and then sort that array.

– You can simply use the bubbleSort method which sorts an array of Comparables!

– How will it know how to sort?

Page 33: CS 106 Introduction to Computer Science I 11 / 27 / 2006 Instructor: Michael Eckmann

Interfaces• So, the bubbleSort method that sorts Comparables now can

sort an array of

– Strings

– Cards

– Contacts

– references to any objects whose class implements the Comparable interface

Page 34: CS 106 Introduction to Computer Science I 11 / 27 / 2006 Instructor: Michael Eckmann

Interfaces• Interfaces can have hierarchies just like classes have hierarchies

• That is, an interface can inherit from another interface.

• The child interface inherits everything from the parent interface (all the abstract methods and all the constants.)

• Any class that implements an interface

– must implement the interface's methods and all it's parents' methods

– gets access to all the constants in the child interface and the parents' interfaces

Page 35: CS 106 Introduction to Computer Science I 11 / 27 / 2006 Instructor: Michael Eckmann

Interfaces• Example:

– All these interfaces are made up (they are NOT part of the Java API) – assume that they are interfaces we create ourselves.

– Let's say we have interfaces named Liquid, Drinkable, and TastyDrink.

– Let's assume that the TastyDrink interface inherits from Drinkable. And the Drinkable interface inherits from Liquid.

– A class, say Soda, implements the TastyDrink interface.

– Class Soda must provide implementations of all the abstract methods of TastyDrink, Drinkable and Liquid.

– Class Soda also has access to all the constants in the three interfaces.

Page 36: CS 106 Introduction to Computer Science I 11 / 27 / 2006 Instructor: Michael Eckmann

Interfaces• A big difference between classes and interfaces is in the possible

hierarchies.

• Class hierarchies and interface hierarchies never overlap. They are kept seperate.

• Class hierarchies cannot have multiple inheritance, but interface hierarchies can. Example on board.

• Also, a class can extend only one other class, but can implement any number of interfaces.

• Eg. A class can implement both Comparable and Drinkable.

Page 37: CS 106 Introduction to Computer Science I 11 / 27 / 2006 Instructor: Michael Eckmann

Interfaces• Interfaces can be used as a reference type. Anywhere you can use

other types (primitives or class names) you can use an interface name.

• Only objects of classes that implement the interface are allowed to be assigned to that reference variable.

• Example:

– We just saw that a method can have as a parameter a Comparable variable. (or in our case, an array of Comparables.)

– This means that the only objects that can be passed in to the method must be of a type (a class) that implements Comparable

• This is extremely useful as it allows use to write more generic code.

Page 38: CS 106 Introduction to Computer Science I 11 / 27 / 2006 Instructor: Michael Eckmann

Interfaces & Abstract classes• For more information on Interfaces and abstract classes, see the

following links:

• http://java.sun.com/docs/books/tutorial/java/interpack/QandE/interfaces-questions.html

• http://java.sun.com/docs/books/tutorial/java/javaOO/abstract.html

Page 39: CS 106 Introduction to Computer Science I 11 / 27 / 2006 Instructor: Michael Eckmann

Designing for polymorphism• Polymorphism allows a consistent approach to inconsistent but

related behaviors. What does that mean?

• First examine the problem to find opportunities that lend themselves to this before we write code.

• Let's look at some example situations and discuss them.

Page 40: CS 106 Introduction to Computer Science I 11 / 27 / 2006 Instructor: Michael Eckmann

Designing for polymorphism• Different types of vehicles move in different ways

• All business transactions for a company must be logged

• All products produced by a company must meet certain quality standards

• A hotel needs to plan their remodeling efforts for every room

• A casino wants to analyze the profit margin for their games

• A dispatcher must schedule moving vans and personnel based on the job size

• A drawing program allows the user to draw various shapes

Page 41: CS 106 Introduction to Computer Science I 11 / 27 / 2006 Instructor: Michael Eckmann

ArrayList• This is a good time to bring up a class in Java API named

ArrayList, because it works on general Objects.

• ArrayList is a class in the Java API

• It can store different types of data into an “array”

• An ArrayList can change size throughout the lifetime of the program

– whereas a regular array is a fixed size

• An ArrayList actually stores references to objects, not the objects themselves

• This means that we cannot store values of primitive types directly -- we have to use the wrapper classes if we want to do that.

Page 42: CS 106 Introduction to Computer Science I 11 / 27 / 2006 Instructor: Michael Eckmann

ArrayList• Some ArrayList methods

– ArrayList() --- constructor

– boolean add(Object o) – add the object reference to the end of the list

– void add(int index, Object o) – add the object reference to the list at the index

– void clear() -- remove all elements from the list

– Object get(int index) – return the object reference at that index in the list

– int indexOf(Object o) – returns the index of the first occurrence of o

– boolean isEmpty() -- returns true if the list contains no elements, false otherwise

Page 43: CS 106 Introduction to Computer Science I 11 / 27 / 2006 Instructor: Michael Eckmann

ArrayList• Some ArrayList methods

– Object remove(int index) – returns the object reference at that index in the list and removes it from the list

– int size() – returns the number of elements in the list

– boolean contains(Object o) -- returns true if the list contains o, false otherwise

– void ensureCapacity(int minCapacity) – tells Java to ensure that the list will be able to contain at least minCapacity references

– int lastIndexOf(Object o) – what do you think this does?

– boolean remove(Object o) -- removes a single instance of o from the list

– protected void removeRange(int fromIndex, int toIndex) --removes from the list all of the elements whose index is between fromIndex, inclusive and toIndex, exclusive.

Page 44: CS 106 Introduction to Computer Science I 11 / 27 / 2006 Instructor: Michael Eckmann

ArrayList• Some ArrayList methods

– Object set(int index, Object o) -- replaces the element at the specified index in this list with o.

– What if this method wasn't in the class. How might you achieve that functionality?

Page 45: CS 106 Introduction to Computer Science I 11 / 27 / 2006 Instructor: Michael Eckmann

ArrayList• Let's create an ArrayList of different types and add some elements to it

and remove some, etc...

• When we create one that allows different types, we have to cast any returned Objects from methods to be the type we want.

• Because Java implemented ArrayLists generically, and because of the way Java decided to have the class hierarchy such that all classes have Object as their superclass, this usefulness of ArrayLists is dramatically increased over a class that may have only allowed one type for its elements.

• So, that's a large benefit of good object oriented design --- generality --- so that you (or the Java implementers themselves) don't have to implement multiple classes to work on multiple types.

• If you create your class hierachy well, lots of stuff can be done generically (e.g. Have code that works on all Pets instead of just Dog or Cat objects for instance.)

Page 46: CS 106 Introduction to Computer Science I 11 / 27 / 2006 Instructor: Michael Eckmann

ArrayList• If we stored several different types of data in a list, we may not know at

some point what type of object is actually stored in a particular index of the ArrayList.

• How do we find out what type a particular object actually is?

Page 47: CS 106 Introduction to Computer Science I 11 / 27 / 2006 Instructor: Michael Eckmann

ArrayList• If we stored several different types of data in a list, we may not know at

some point what type of object is actually stored in a particular index of the ArrayList.

• How do we find out what type a particular object actually is?

• We can use the instanceof operator to check if some reference is an instance of some type.

e.g.

Object o = somearraylist.get(0);

if (o instanceof Contact)

{

//then cast o to be a Contact and use it

}

Page 48: CS 106 Introduction to Computer Science I 11 / 27 / 2006 Instructor: Michael Eckmann

ArrayList• Let's look at how each method affected the list and what they returned.

– ArrayList() , boolean add(Object o) ,

– void add(int index, Object o) , void clear() , Object get(int index) ,

– int indexOf(Object o) , boolean isEmpty() ,

– Object remove(int index) , int size() , boolean contains(Object o) ,

– void ensureCapacity(int minCapacity) ,

– int lastIndexOf(Object o) , boolean remove(Object o) ,

– protected void removeRange(int fromIndex, int toIndex)

Page 49: CS 106 Introduction to Computer Science I 11 / 27 / 2006 Instructor: Michael Eckmann

Polymorphism via Inheriance• An ArrayList uses polymorphism because it holds

references to objects of Object.

• An Object reference can be used to refer to any object (of any type)!!!