1 / 22

Chapter 13: Inheritance and Polymorphism

Chapter 13: Inheritance and Polymorphism. CS180 Fall 2006. Announcements. Project 5 grading is… wait for it… wait for it…DONE! Grades will be released by early next week Gradesheets handed back in your labs Hand back exam 2 Mean: 67.8 Median: 71 High: 97 Next week: generics

Leo
Download Presentation

Chapter 13: Inheritance and Polymorphism

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 13: Inheritance and Polymorphism CS180 Fall 2006

  2. Announcements • Project 5 grading is… wait for it… wait for it…DONE! • Grades will be released by early next week • Gradesheets handed back in your labs • Hand back exam 2 • Mean: 67.8 • Median: 71 • High: 97 • Next week: generics • Online chapter • You should be able to access it with the password that came with your book (if you bought it in the bookstore) • Or… go here: http://www.cs.purdue.edu/~mrcarlso/cs180 • We will provide a user/password for you

  3. Definitions • Inheritance – object oriented way to form new classes from pre-existing ones • Superclass • The parent class • If class is final, cannot inherit from this class • Subclass • Class which inherits all non-private properties from the superclass • Generally a specific instance of a superclass (Animal->Ferret) • Polymorphism – a object can take many forms • Not all animals are ferrets, could be platypus’s as well • A makeSound() method may be different for a ferret and a platypus • Combining the two, can create subclasses with different properties • Your platypus class may have a swim() method, but ferrets cannot swim!

  4. Inheriting From the Superclass • Two ways • Use the protected keyword instead of the private keyword • Variables and methods which are protected are accessible by the subclass, but not the world • Use public for methods to inherit, private for methods to not inherit and all variables • Variables no longer accessible directly in subclass • Use accessors and mutators to modify them • Overwrite public (or protected) methods as necessary • If a method is declared final, then it cannot be overwritten in a subclass • Can also overload methods if desired • Constructors • Not inherited! Must rewrite them • Use super keyword to call superconstructor from parent class • Can only use super as first line of a constructor • If no superconstructor is explicitly called, then super() (the default superconstructor) is automatically called as the first line • super keyword can also be used to call instances of methods from superclasses

  5. Syntax • To extend a class, use the extends keyword • The class will now inherit all non-private characteristics of the superclass • Do not have to re-write methods which are the same • Can introduce new methods and/or variables public class A { private int x; public A() { set(0); } public A(int x) { set(x); } public void set(int x) { this.x = x; } public int get() { return x; } public void add1() { bump(); } private void bump() { x++; } } public class B extends A { public B() { super(); } public B(int x) { super(x); } public void add1() { set(get()+1); } }

  6. Inheriting From the Superclass public class A { protected int x; public A() { set(0); } public A(int x) { set(x); } public void set(int x) { this.x = x; } public int get() { return x; } public void add1() { bump(); } private void bump() { x++; } } public class B extends A { public B() { super(); } public B(int x) { super(x); } } public class A { private int x; public A() { set(0); } public A(int x) { set(x); } public void set(int x) { this.x = x; } public int get() { return x; } public void add1() { bump(); } private void bump() { x++; } } public class B extends A { public B() { super(); } public B(int x) { super(x); } public void add1() { set(get()+1); } } The add1() method is overwritten here!

  7. Inheriting From the Superclass On the superclass constructor calls, constructors are executed top-down on the hierarchy. public class A { A() { SOP(“A”); } } public class B extends A { public B() { SOP(“B”); } } public class C extends A { public C() { SOP(“C”); } } public class D extends B { public D() { SOP(“D”); } } A = new A(); Output: A B = new B(); Output: AB C = new C(); Output: AC D = new D(); Output: ABD

  8. Object Class • Class Object is the superclass of all superclasses in Java • All classes defined implicitly inherit from Object if not explicitly extending from another class • Even if explicitly extending another class, that other class either extends from another class or implicitly extends from Object • Some useful methods which are commonly overwritten • equals – for comparisons (defaults to reference address comparision) • toString – translates your object into an appropriate String (defaults to the reference address)

  9. Polymorphism public class Animal { protected int age; public void makeSound() { SOP(“Make sound!”); } } public class Ferret extends Animal { public Ferret() { super(); } public void eatSweets() { SOP(“Yummy!”); } public void makeSound() { SOP(“Squeal!”); } } public class Platypus extends Animal { public Platypus() { super(); } public void swim() { SOP(“Swim!”); } public void makeSound() { SOP(“Quack!”); } } _____________________________________________ Animal a = new Ferret(); a.swim(); // illegal! Not all animals know how to swim! a.makeSound(); // legal! All animals make sounds! a.eatSweets(); // illegal! Only ferrets like candies and cookies! • Allows a variable to take on many forms • A variable of type Animal may point to may different types of animals • Only methods scoped within the variable type are available • Not all animals swim, so even though an Animal object may point to a platypus, you cannot call the swim() method

  10. Dynamic Binding • On the call the makeSound(), what happens? • If Animal object a is a Platypus, then “Quack!” • If Animal object a is a Ferret, then “Squeal!” • Why not “Make sound!”?  dynamic binding! • Objects have two types • Static type – the type of the variable name • Dynamic type – the “actual type” of the variable in memory • Dynamic binding • Used for method lookup • Look up “most specific” instance of method call (look up the method in the dynamic type if it exists) • Most specific instance of a method may be in a parent class

  11. Dynamic Binding public class A { protected int x; public A() { set(0); } public A(int x) { set(x); } public void set(int x) { this.x = x; } public int get() { return x; } public void bump() { x+=2; } } public class B extends A { public B() { super(); } public B(int x) { super(x); } public void bump() { x++; } } static type dynamic type A a = new B(); a.bump(); SOP(“a=“+a.get()); Object a is of static type A, dynamic type B. On a method call, use dynamic type first!

  12. Determining Class Type • In order to access a method in a subclass from an object with a static type of the superclass, need to downcast • Downcasting is unsafe! Need to know that downcast is legal. • Use instanceof keyword or other methods • x instanceof A – true if x is an instance of class A or a subclass of A • x.getClass().equals(A.class) – true if x is an instance of class A • A.class.isAssignableFrom(x.getClass()) is true if x is an instance of class A or a subclass of A

  13. Determining Class Type public class Animal { protected int age; public void makeSound() { SOP(“Make sound!”); } } public class Ferret extends Animal { public Ferret() { super(); } public void eatSweets() { SOP(“Yummy!”); } public void makeSound() { SOP(“Squeal!”); } } public class Platypus extends Animal { public Platypus() { super(); } public void swim() { SOP(“Swim!”); } public void makeSound() { SOP(“Quack!”); } } Animal a = new Ferret(); if (a instanceof Ferret) ((Ferret)a).eatSweets(); a = new Platypus(); if (a.getClass() == Platypus.class) ((Platypus)a).swim(); if (Platypus.class.isAssignableFrom(a)) ((Platypus)a).swim(); ________________________________ Animal a = new Ferret(); ((Platypus)a).swim(); // compiles, but runtime error!

  14. Abstract Classes • Sometimes a superclass never needs to be instantiated – you only make instances of the subclasses • Make class abstract • Cannot be instantiated • May have some methods be abstract • Is like a blueprint for subclasses, with methods that need to be filled in public abstract class Animal { protected int age; public abstract void makeSound(); } public class Ferret extends Animal { public Ferret() { super(); } public void eatSweets() { SOP(“Yummy!”); } public void makeSound() { SOP(“Squeal!”); } } public class Platypus extends Animal { public Platypus() { super(); } public void swim() { SOP(“Swim!”); } public void makeSound() { SOP(“Quack!”); } }

  15. Interfaces • Contains method headers • Cannot instantiate interface • Cannot have any non-final variables • A class can implement many interfaces • Interfaces can extend from each other • Example: Comparable • Contains one method, compareTo, which takes two objects and compares them • Returns a negative number if less than • Returns 0 if equal to • Returns a positive number if greater than • Comparable is an interface and not an abstract class because not all things comparable are related • Numbers and people are both comparable, but have no reasonable relationship between them

  16. Interfaces public interface I { public void doStuff(); } public interface J extends I { public void doMoreStuff(); } public interface K { public void doEvenMoreStuff(); } public class A implements J, K { public void doStuff() {…} public void doMoreStuff() {…} public void doEvenMoreStuff {…} } J extends I, so interface J actually has 2 methods: doStuff() and doMoreStuff(). A implements J and K, so A must have a method for each method in the interfaces it implements.

  17. Putting It All Together public interface SoundMaker { public void makeSound(); } public interface EggLayer { public void layEgg(); } public interface Swimmer { public void swim(); } public abstract class Animal implements SoundMaker { protected int age; public abstract void makeSound(); } public class Ferret extends Animal { public Ferret() { super(); } public void eatSweets() { SOP(“Yummy!”); } public void makeSound() { SOP(“Squeal!”); } } public class Platypus extends Animal implements EggLayer, Swimmer { public Platypus() { super(); } public void swim() { SOP(“Swim!”); } public void makeSound() { SOP(“Quack!”); } public void layEgg() { SOP(“Egg layed!”); } } public class Trumpet extends SoundMaker { public void makeSound() { SOP(“Toot!”); } } Images taken from Wikipedia.

  18. Abstract Class vs. Interface • Abstract classes are blueprints, interfaces are contracts • Interface: “Here’s some methods. If your class implements this interface, you must provide an implementation of each method in the interface in the class.” • Method headers • final variables • A class can implement multiple interfaces • Cannot instantiate • Abstract class: “Here’s a blueprint for a class. If your class extends this abstract class, you can use any functionality here and add onto it, but you must fill in what I have not.” • Abstract method headers • Methods • Variables • A class can extend only one class • Cannot instantiate

  19. Next Week, in CS180…(think: TV show voiceover…) • Recall that arrays are fixed in size • Dynamic data structures allow us to create collections of objects which vary in size • Many found in java.util • Standard collections • Vector (a resizable array) • LinkedList (a chain of objects) • ArrayList (a hybrid of vectors and linked lists) • Special collections • Queue (interface first in first out structure) • Stack (last in first out structure) • We will talk about these structures in much more detail next week with generics (stay tuned…)

  20. Static Binding (optional) • The keyword static means that a variable or method lookup is resolved at compile time • In Java… • Methods in a class are dynamically bound (unless said to be static) • Lookup resolved at runtime with dynamic binding • Variables in a class are statically bound • Use static binding to lookup values • This rarely occurs unless you make your variables public (which… you shouldn’t)

  21. Static Binding (optional) public class A { public int x; public A() { set(0); } public A(int x) { set(x); } public void set(int x) { this.x = x; } public int get() { return x; } public void bump() { x+=2; } } public class B extends A { public B() { super(); } public B(int x) { super(x); } public void bump() { x++; } } A a = new B(); a.bump(); SOP(“a=“+a.x); B b = new B(4); b.set(15); SOP(“b=“+b.x); b’s static and dynamic type are both B. On the call to set, dynamic binding dictates that the set method in class A is called. Since we are in class A, the variable x, statically bound, is used.

  22. Static Binding (optional) public class A { public int x; public A() { set(0); } public A(int x) { set(x); } public void set(int x) { this.x = x; } public int get() { return x; } public void bump() { x+=2; } } public class B extends A { public int x = -1; public B() { super(); } public B(int x) { super(x); } public void bump() { x++; } } A a = new B(); a.bump(); SOP(“a=“+a.x); B b = new B(4); b.set(15); SOP(“b=“+b.x); b’s static and dynamic type are both B. On the call to set, dynamic binding dictates that the set method in class A is called. Since we are in class A, the variable x in class A, statically bound, is used. However, in the print out, x is statically retrieved from a B static type object, and thus -1 is printed out. Moral: None of this happens if 1) your variables are private, and 2) you don’t re-declare the same objects in a subclass!

More Related