lecture31

lecture31 - COMP 250 Winter 2010 31 - polymorphism March...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: COMP 250 Winter 2010 31 - polymorphism March 31, 2010 [updated April 3] Polymorphism Suppose you have some reference variable. It is is declared to be a certain type. You might assume that this means that the variable can point only to objects that are of that type 1 . However, this would too be limiting a requirement. For example, Java allows us to write: Dog mydog = new Beagle(Buddy); even though we have two types in this statement. It makes sense to allow this definition because Beagle is a subclass of Dog . Any object that belongs to class Beagle also belongs to class Dog . We say that the variable myDog is polymorphic (from Latin: poly means many and morph means forms), because it can refer to objects of class Dog or it can refer to objects that belong to a subclass of Dog , such as Beagle . More generally, we say references in Java are polymorphic in that they can refer to objects of several different types, namely the variables declared type (which is determined at compile time, sometimes called the static type) and there is the dynamic type, namely the type of the object referenced at runtime. At runtime, a variable can reference any object that belongs to the class (or a subclass) of the declared type. (The distinction between class and type will arise later, when we discuss interfaces.) Several issues arise. First, why not just declare myDog to be of type Beagle ? The reason is that it could happen that later we may want myDog to point to a different dog. e.g. my first dog Buddy the Beagle died long ago, and recently I got a new dog mydog = new Poodle(Willie); Note that by declaring myDog to be of type Dog , we are not allowing myDog to invoke methods that are only in subclasses of Dog . For example, beagles are hounds: they chase rabbits and are used for hunting. Many other dogs dont do this. So if class Beagle had a method hunt() , then we would not be allowed to say myDog.hunt() if myDog were of type Dog . The Java compiler will not allow it since hunt() is not defined in class Dog , but rather it is only defined in subclass Beagle and perhaps other subclasses....
View Full Document

This note was uploaded on 09/25/2011 for the course COMP 250 taught by Professor Blanchette during the Spring '08 term at McGill.

Page1 / 4

lecture31 - COMP 250 Winter 2010 31 - polymorphism March...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online