Slide 1Slide 2Slide 3Slide 4Slide 5Slide 6Slide 7Slide 8Slide 9Classes InheritanceSlide 11Abstract Methods and ClassesAbstract Methods and ClassesPolymorphismDynamic Dispatch and PolymorphismType Consistency in Class HierarchiesChecking Object TypesBeware of instanceofPolymorphism VersionCSE 131 Computer Science 1Module 10: Hierarchiesclass inheritance and class hierarchies2345678910Classes InheritanceClasses may form a hierarchy (general specific) »Capture common features in a general class Java allows such hierarchy: a new class can extend an existing class»the new class is called the subclass »the original is called the superclass»the subclass inherits all data and methodsin its superclassAccess permissions for subclass»private instance variables and methods can only be accessedwithin the class they belong to»protected instance variables andmethods can be accessed bysubclassesShape- lineColor- lineStyleOneDim- startStyle- endStyleLine- p1, p2Curve- p[..]TwoDim- fillColorRect- center- width- heightEllipse- radius1- radius211To extend a class, use the extends keyword» public class Ellipse extends twoDim { ... }Using inherited methods»Superclass has a method foo(){…}»A subclass can use foo() without defining it itselfA subclass can override a method from a superclass»Superclass has foo(){…}; a subclass can re-define and thus override foo(){…};»can access superclass’ version of a method foo as super.foo(..)A subclass constructor may invoke its superclass’ constructor using super(..)12Abstract Methods and ClassesA class can claim an abstract method without defining it»Leave it for its subclass to defineA class with one or more abstract methods is called an abstract class and must be labeled abstractpublic abstract class twoDim extends Shape { ...public abstract double area();}public class Rect extends twoDim { ..double width, height; ...public double area() { return width*height; }}One cannot create objects belonging to an abstract class»but can create objects belonging to “concrete” subclasses»a concrete subclass of an abstract class must define all abstract methods of its superclasses13Abstract Methods and ClassesAn abstract method is a method that is identified in a superclass and defined in its subclassesA class with one or more abstract methods is called an abstract class and must be labeled abstractpublic abstract class Animal { ...public abstract String speak();}public class Cat extends Animal { ..public String speak() { return “Meow”; }}One cannot create objects belonging to an abstract class»but can create objects belonging to “concrete” subclasses»E.g. Animal x = new Cat();»The type at declaration stays forever. For example, the type of x is Animal, not Cat.14PolymorphismA class hierarchy may contain multiple “versions” of the same methodJava determines at runtime which version of a method to runthis is called dynamic method dispatching15Dynamic Dispatch and PolymorphismThis allows us to process a collection of related but distinct items in a consistent wayExample:public void speaking(Animal x ) { x.speak(); }let each animal speak its own language, using the appropriate speak() method for each animal»this is an example of polymorphism16Type Consistency in Class HierarchiesWe can use an object of a subclass, anywhere a superclass object is called for» Animal x = new Bear();Sometimes, we want to use a superclass object where a subclass is required»this requires a cast: Animal x = new Bear(); // now I want to create a same Bear Bear y = (Bear) x;»typically, we “know” the object has the appropriate typeWe can never cast “across the hierarchy”Superclass method can’t use a subclass’s own methods»x.hibernate() is NOT OK»y.hibernate() is OK»((Bear)x).hibernate() is OK »Read http://stackoverflow.com/questions/10021603/calling-a-subclass-method-from-superclass17Checking Object TypesThe instanceof operator can be used to distinguish objects of different types »if (x instanceof Cat) { /* process cats */ } else { /* process other animals */ }lets us apply case-specific processing for different types»note: instanceof is true for subtypes of the specified class•that is, if x is a Cat, (x instanceof Animal) is trueThe getClass() method can be used to check if two objects have exactly the same type»so, (x.getClass() == y.getClass()) is true if x and y are both Cats, but not if x is a Cat and y is an Animal18Beware of instanceofUse it only as a last resort»It defeats the purpose of polymorphism"Anytime you find yourself writing code of the form "if the object is of type T1, then do something, but if it's of type T2, then do something else," slap yourself. -- Scott Meyerspublic final class BadInstanceOf { public void move(Animal aAnimal){ if (aAnimal instanceof Fish){ Fish fish = (Fish)aAnimal; fish.swim(); } else if (aAnimal instanceof Spider){ Spider spider = (Spider)aAnimal; spider.crawl(); }} public class Fish extends Animal { public void swim(){} } public class Spider extends Animal { public void crawl(){} } }19Polymorphism Versionpublic abstract class Animal{ public abstract void move(); } public class Fish extends Animal{ public void move() { swim();} void swim() { ….} } public class Spider extends Animal{ public void move() { crawl();} void crawl() { ….} } …. public class NoInstanceOf { public void move(Animal aAnimal){ aAnimal.move();
View Full Document