1 / 91

Inheritance and Polymorphism

Inheritance and Polymorphism. This section is not required material!!!!. A note about inheritance… It’s not normally covered in 101 It will be gone over in more detail in CS 201 Ask questions if you are confused about inheritance You aren’t the only one!. Motivation.

stuartm
Download Presentation

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. Inheritance and Polymorphism

  2. This section is not required material!!!! • A note about inheritance… • It’s not normally covered in 101 • It will be gone over in more detail in CS 201 • Ask questions if you are confused about inheritance • You aren’t the only one!

  3. Motivation • Consider a transportation computer game • Different types of vehicles: • Planes • Jets, helicopters, space shuttle • Automobiles • Cars, trucks, motorcycles • Trains • Diesel, electric, monorail • Ships • … • Let’s assume a class is written for each type of vehicle

  4. More on classes vs. objects

  5. Motivation • Sample code for the types of planes: • fly() • takeOff() • land() • setAltitude() • setPitch() • Note that a lot of this code is common to all types of planes • They have a lot in common! • It would be a waste to have to write separate fly() methods for each plane type • What if you then have to change one – you would then have to change dozens of methods

  6. Motivation • Indeed, all vehicles will have similar methods: • move() • getLocation() • setSpeed() • isBroken() • Again, a lot of this code is common to all types of vehicles • It would be a waste to have to write separate move() methods for each vehicle type • What if you then have to change one – you would then have to change dozens of methods • What we want is a means to specify one move() method, and have each vehicle type inherit that code • Then, if we have to change it, we only have to change one copy

  7. Motivation • Provides: • move() • getLocation() • setSpeed() • isBroken() • Provides: • fly() • takeOff() • land() • setAltitude() • setPitch() • Provides: • oilChange() • isInTraffic() • Provides: • derail() • getStation()

  8. Motivation • What we will do is create a “parent” class and a “child” class • The “child” class (or subclass) will inherit the methods (etc.) from the “parent” class (or superclass) • Note that some classes (such as Train) are both subclasses and superclasses

  9. Another example • Consider shapes in a graphics program • Shape class • Circle class • Cube class • Dodecahedron class

  10. Today’s demotivators

  11. Inheritance • Organizes objects in a top-down fashion from most general to least general • Inheritance defines a “is-a” relationship • A mountain bike “is a” kind of bicycle • A SUV “is a” kind of automobile • A border collie “is a” kind of dog • A laptop “is a” kind of computer

  12. Musical instrument hierarchy

  13. Musical instrument hierarchy • The hierarchy helps us understand the relationships and similarities of musical instruments • A clarinet “is a” kind of reeded instrument • Reeded instruments “are a” kind of aerophone • The “is-a” relationship is transitive • A clarinet “is a” kind of reeded instrument • A reeded instrument “is a” kind of aerophone • A clarinet “is a” kind of aerophone

  14. Reeded Musical Clarinet Aerophone Instrument Instrument Object-oriented terminology • In object-oriented programming languages, a class created by extending another class is called a subclass • The class used for the basis is called the superclass • Alternative terminology • The superclass is also referred to as the base class • The subclass is also referred to as the derived class

  15. z-axis y-axis (x, y, z) x-axis ThreeDimensionalPoint • Build a new class ThreeDimensionalPoint using inheritance • ThreeDimensionalPoint extends the awt class Point • Point is the superclass (base class) • ThreeDimensionalPoint is the subclass (derived class) • ThreedimensionalPoint extends Point by adding a new property to Point—a z-coordinate

  16. Class ThreeDimensionalPoint See next slide package geometry; import java.awt.*; public class ThreeDimensionalPoint extends Point { // private class constant  private final static int DEFAULT_Z = 0; // private instance variable  private int z = DEFAULT_Z; • Note that ThreeDimensionalPoint inherits the variables in the Point class • Thus, it has an x and y variables (inherited from Point) • And it has a z variable (defined above) Keyword extends indicatesthat ThreeDimensionalPointis a subclass of Point New instance variable

  17. Packages • Allow definitions to be collected together into a single entity—a package • ThreeDimensionalPoint will be added to the geometry package • Classes and names in the same package are stored in the same folder • Classes in a package go into their own namespace and therefore the names in a particular package do not conflict with other names in other packages • For example, a package called Graph might have a different definition of ThreeDimensionalPoint • When defining members of a class or interface, Java does not require an explicit access specification. The implicit specification is known as default access. Members of a class with default access can be accessed only by members of the package.

  18. About extends • If class A extends class B • Then class A is the subclass of B • Class B is the superclass of class A • A “is a” B • A has (almost) all the methods and variables that B has • If class Train extends class Vehicle • Then class Train is the subclass of Vehicle • Class Vehicle is the superclass of class Train • Train “is a” Vehicle • Train has (almost) all the methods and variables that Vehicle has

  19. Java’s Mother-of-all-objects—Class Object

  20. Thus, everything extends Object • Either directly or indirectly • So what does that give us? • Object contains the following methods: • clone() • equals() • toString() • and others… • Thus, every class has those methods

  21. Fan-supplied demotivators!

  22. Class ThreeDimensionalPoint (review from last time) See next slide package geometry; import java.awt.*; public class ThreeDimensionalPoint extends Point { // private class constant  private final static int DEFAULT_Z = 0; // private instance variable  private int z = DEFAULT_Z; • Note that ThreeDimensionalPoint inherits the variables in the Point class • Thus, it has an x and y variables (inherited from Point) • And it has a z variable (defined above) Keyword extends indicatesthat ThreeDimensionalPointis a subclass of Point New instance variable

  23. A note about equals() • Why does the equals() method always have to have the following prototype: • boolean equals(Object obj) • Many other class in the Java SDK require the user of equals() • Such as the Vector class • Those classes need to know how the equals() method will work in order for them to work properly • Thus, it must have the same prototype

  24. ThreeDimensionalPoint • Methods toString(), equals() , and clone() should not have different signatures from the Point versions ThreeDimensionalPoint c = new ThreeDImensionalPoint(1, 4, 9); ThreeDimensionalPoint d = (ThreeDimensionalPoint) c.clone(); String s = c.toString(); boolean b = c.equals(d); Cast is necessary as return type of subclass methodclone() is Object Invocation of subclasstoString() method Invocation of subclassequals() method

  25. ThreeDimensionalPoint • Accessors and mutators // getZ(): z-coordinate accessor  publicdouble getZ() { return z; } // setZ(): y-coordinate mutator  publicvoid setZ(int value) { z = value; }

  26. ThreeDimensionalPoint • Constructors // ThreeDimensionalPoint(): default constructor  public ThreeDimensionalPoint() { super(); } // ThreeDimensionalPoint(): specific constructor  public ThreeDimensionalPoint(int a, int b, int c) { super(a, b); setZ(c); }

  27. ThreeDimensionalPoint • Facilitators // translate(): shifting facilitator  publicvoid translate(int dx, int dy, int dz) { translate(dx, dy); int zValue = (int) getZ(); setZ(zValue + dz); } calls the inherited translate method in Point

  28. ThreeDimensionalPoint ThreeDimensionalPoint a =new ThreeDimensionalPoint(6, 21, 54); a.translate(1, 1);    // invocation of superclass translate() a.translate(2, 2, 2); // invocation of 3DPoint’s translate() • Java determines which method to use based on the number of parameters in the invocation • After the first call to translate, what is the value of a? • After the second call to translate, what is the value of a? • Note that this is still overloading!

  29. ThreeDimensionalPoint • Facilitators // toString(): conversion facilitator  public String toString() { int a = (int) getX(); int b = (int) getY(); int c = (int) getZ(); return getClass() + "[" + a + ", " + b + ", " + c + "]"; } • What’s getClass()?

  30. ThreeDimensionalPoint • Facilitators // equals(): equality facilitator  publicboolean equals(Object v) { if (v instanceof ThreeDimensionalPoint) { ThreeDimensionalPoint p = (ThreeDimensionalPoint) v; int z1 = (int) getZ(); int z2 = (int) p.getZ(); returnsuper.equals(p) && (z1 == z2); } else { returnfalse; } } calls the inherited equals method in Point

  31. ThreeDimensionalPoint • Facilitators // clone(): clone facilitator  public Object clone() { int a = (int) getX(); int b = (int) getY(); int c = (int) getZ(); returnnew ThreeDimensionalPoint(a, b, c); }

  32. Today’s demotivators

  33. ColoredPoint • Suppose an application calls for the use of colored points. • We can naturally extend class Point to create ColoredPoint • Class ColoredPoint will be added to packagegeometry package geometry; import java.awt.*; public class ColoredPoint extends Point { // instance variable  Color color;…

  34. Class hierarchy Object Point ThreeDimPoint ColoredPoint

  35. ColoredPoint • Constructors // ColoredPoint(): default constructor  public ColoredPoint() { super(); setColor(Color.blue); } // ColoredPoint(): specific constructor  public ColoredPoint(int x, int y, Color c) { super(x, y); setColor(c); }

  36. ColoredPoint • Accessors and mutators // getColor(): color property accessor  public Color getColor() { return color; } // setColor(): color property mutator  publicvoid setColor(Color c) { color = c; }

  37. ColoredPoint • Facilitators // clone(): clone facilitator  public Object clone() { int a = (int) getX(); int b = (int) getY(); Color c = getColor(); returnnew ColoredPoint(a, b, c); }

  38. ColoredPoint • Facilitators // toString(): string representation facilitator  public String toString() { int a = (int) getX(); int b = (int) getY(); Color c = getColor(); return getClass() + "[" + a + ", " + b + ", " + c + "]"; }

  39. ColoredPoint • Facilitators // equals(): equal facilitator  publicboolean equals(Object v) { if (v instanceof ColoredPoint) { Color c1 = getColor(); Color c2 = ((ColoredPoint) v).getColor(); returnsuper.equals(v) && c1.equals(c2); } else { returnfalse; }

  40. Colored3DPoint • Suppose an application needs a colored, three-dimensional point. • Can we create such a class by extending both ThreeDimensionalPoint and ColoredPoint?

  41. Proposed class hierarchy Object Point ThreeDimPoint ColoredPoint Colored3DPoint

  42. Colored3DPoint • Java does not support multiple inheritance • Java only supports single inheritance • C++ does support multiple inheritance package Geometry; import java.awt.*; public class Colored3DPoint extends ThreeDimensionalPoint { // instance variable  Color color;

  43. Class hierarchy Object Point ThreeDimPoint ColoredPoint Colored3DPoint

  44. Colored3DPoint • Constructors // Colored3DPoint(): default constructor  public Colored3DPoint() { setColor(Color.blue); } // Colored3DPoint(): specific constructor  public Colored3DPoint(int a, int b, int c, Color d) { super(a, b, c); setColor(d); }

  45. Colored3DPoint • Accessors and mutators // getColor(): color property accessor  public Color getColor() { return color; } // setColor(): color property mutator  public void setColor(Color c) { color = c; }

  46. Colored3DPoint • Facilitators // clone(): clone facilitator  public Object clone() { int a = (int) getX(); int b = (int) getY(); int c = (int) getZ(); Color d = getColor(); returnnew Colored3DPoint(a, b, c, d); }

  47. Colored3DPoint • Facilitators // toString(): string representation facilitator  public String toString() { int a = (int) getX(); int b = (int) getY(); int c = (int) getZ(); Color d = getColor(); return getClass() + "[" + a + ", " + b + ", " + c + ", " + d + "]"; }

  48. Colored3DPoint • Facilitators // equals(): equal facilitator  publicboolean equals(Object v) { if (v instanceof Colored3DPoint) { Color c1 = getColor(); Color c2 = ((Colored3DPoint) v).getColor(); returnsuper.equals(v) && c1.equals(c2); } else { returnfalse; }

  49. Overriding • Consider the following code: class Foo { // automatically extends Object public String toString () { return “Foo”; } } ... Foo f = new Foo(); System.out.println (f); • Now there are two toString() method defined • One inherited from class Object • One defined in class Foo • And they both have the same prototype! • Which one does Java call?

  50. Overriding • Java will call the most specific overriden method it can • toString() in Foo is more specific than toString() in Object • Consider our transportation hierarchy: • Assume each class has its own toString() method • Car extends Automobile extends Vehicle (extends Object) • Assume each defines a toString() methods • The toString() method in Vehicle is more specific (to vehicles) than the one in Object • The toString() method in Automobiles is more specific than the ones in Vehicle or Object • The toString() method in Car is more specific than the ones in Automobile, Vehicle, or Object • Thus, for a Car object, the Car toString() will be called • There are ways to call the other toString() methods • This has to be specifically requested

More Related