1 / 41

CS1101: Programming Methodology comp.nus.sg/~cs1101x/

Explore the role of inheritance in object-oriented design and demonstrate the power of polymorphism and late binding of methods. Develop a series of classes to showcase the inheritance mechanism in Java, and learn about superclasses, subclasses, and access modifiers.

annieborden
Download Presentation

CS1101: Programming Methodology comp.nus.sg/~cs1101x/

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. CS1101: Programming Methodologyhttp://www.comp.nus.edu.sg/~cs1101x/

  2. Lecture 13: Inheritance and Polymorphism • Explore the role of inheritance in object-oriented design. • Demonstrate the power of polymorphism and the late binding of methods. • Develop a series of classes demonstrating the power of the inheritance and polymorphism mechanism. • Explore the nuances of superclasses and subclasses in Java. • Consider the roles of protected access and default access in information hiding. • Introduce abstract classes and interfaces. • Provides an appreciation for the use of modifier final with classes and methods. Acknowledgement: Cohoon and Davidson.

  3. 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

  4. Point (1/2) Data fields: public int x; // x-coordinate public int y; // y-coordinate Constructors: Point() // constructs point at (0,0) Point(int x, int y) // constructs point at (x,y) Point(Point p) // constructs point at location p Methods: double getX() // returns x-coordinate double getY() // returns y-coordinate translate(int dx, int dy) // translate this point by dx along the x-axis // and dy along the y-axis See API specification for complete information: http://java.sun.com/j2se/1.5.0/docs/api/java/awt/Point.html

  5. Point (2/2) import java.awt.Point; public class PointDemo { public static void main(String[] args) { Point p = new Point(2,3); System.out.println(p); p.translate(10,12); System.out.println("After translation:"); System.out.println(p); } } +

  6. See next slide. Keyword ‘extends’ indicatesthat ThreeDimensionalPointis a subclass of Point. New instance variable. Exception for Point. Class ThreeDimensionalPoint package Geometry; import java.awt.*; public class ThreeDimensionalPoint extends Point { // private class constant private final static int DEFAULT_Z = 0; // instance variable  public int z = DEFAULT_Z;

  7. Using ThreeDimensionalPoint (1/2) ThreeDimensionalPoint a =new ThreeDimensionalPoint(6, 21, 54); a.translate(1, 1);    // invocation of superclass translate() a.translate(2, 2, 2);// invocation of subclass 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?

  8. Cast is necessary as return type of subclass method clone() is Object. Invocation of subclass toString() method. Invocation of subclass equals() method. Using ThreeDimensionalPoint (2/2) • 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);

  9. Defining ThreeDimensionalPoint (1/7) package Geometry; import java.awt.*; public class ThreeDimensionalPoint extends Point { // private class constant private final static int DEFAULT_Z = 0; // instance variable  public int z = DEFAULT_Z;

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

  11. Defining ThreeDimensionalPoint (3/7) • Accessors and mutators // getZ(): z-coordinate accessor  public double getZ() { return z; } // setZ(): y-coordinate mutator  public void setZ(int value) { z = value; }

  12. Defining ThreeDimensionalPoint (4/7) • translate() // translate(): shifting method  public void translate(int dx, int dy, int dz) { translate(dx, dy); int zValue = (int) getZ(); setZ(zValue + dz); }

  13. Defining ThreeDimensionalPoint (5/7) • toString() // toString(): string representation method public String toString() { int a = (int) getX(); int b = (int) getY(); int c = (int) getZ(); return getClass() + "[" + a + ", " + b + ", " + c + "]"; }

  14. Defining ThreeDimensionalPoint (6/7) • equals() // equals(): equality method public boolean equals(Object v) { if (v instanceof ThreeDimensionalPoint) { ThreeDimensionalPoint p = (ThreeDimensionalPoint) v; int z1 = (int) this.getZ(); int z2 = (int) p.getZ(); returnsuper.equals(p) && (z1 == z2); } else return false; }

  15. Defining ThreeDimensionalPoint (7/7) • clone() // clone(): clone method  public Object clone() { int a = (int) getX(); int b = (int) getY(); int c = (int) getZ(); return new ThreeDimensionalPoint(a, b, c); }

  16. ThreeDimensionalPoint Demo public static void main(String[] args) { ThreeDimensonalPoint p = new ThreeDimensionalPoint(2, 3, 8); System.out.println(p); p.translate(1, 2, 3); System.out.println("After translation:"); System.out.println(p); } +

  17. ColoredPoint (1/6) • 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 package Geometry. package Geometry; import java.awt.*; public class ColoredPoint extends Point { // instance variable  Color color;. . .

  18. ColoredPoint (2/6) • 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); }

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

  20. ColoredPoint (4/6) • clone() // clone(): clone method  public Object clone() { int a = (int) getX(); int b = (int) getY(); Color c = getColor(); return new ColoredPoint(a, b, c); }

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

  22. ColoredPoint (6/6) • equals() // equals(): equality method public boolean equals(Object v) { if (v instanceof ColoredPoint) { Color c1 = this.getColor(); Color c2 = ((ColoredPoint) v).getColor(); return super.equals(v) && c1.equals(c2); } else return false; }

  23. ColoredPoint Demo public static void main(String[] args) { ColoredPoint p = new ColoredPoint(6, 2, Color.RED); System.out.println(p); p.translate(3, 1); p.setColor(Color.GREEN); System.out.println("Updated point:"); System.out.println(p); } +

  24. Colored3DPoint (1/6) • Suppose an application needs a colored, three-dimensional point. • Can we create such a class by extending both ThreeDimensionalPoint and ColoredPoint? • No. Java does not support multiple inheritance • Java only supports single inheritance package Geometry; import java.awt.*; public class Colored3DPoint extends ThreeDimensionalPoint { // instance variable  Color color; . . .

  25. Colored3DPoint (2/6) • 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); }

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

  27. Colored3DPoint (4/6) • clone() // clone(): clone method public Object clone() { int a = (int) getX(); int b = (int) getY(); int c = (int) getZ(); Color d = getColor(); return new Colored3DPoint(a, b, c, d); }

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

  29. Colored3DPoint (6/6) • equals() // equals(): equality facilitator  public boolean equals(Object v) { if (v instanceof Colored3DPoint) { Color c1 = this.getColor(); Color c2 = ((Colored3DPoint) v).getColor(); return super.equals(v) && c1.equals(c2); } else return false; }

  30. Break • Abstract classes and Interfaces – 10 minutes • Term Test Questions

  31. Abstract base classes (1/5) • Allows creation of classes with methods that correspond to an abstract concept (i.e., there is not an implementation) • Suppose we wanted to create a class GeometricObject • Reasonable concrete methods include • getPosition() • setPosition() • getColor() • setColor() • paint() • For all but paint(), we can create implementations. • For paint(), we must know what kind of object is to be painted. Is it a square, a triangle, etc. • Method paint() should be an abstract method

  32. Makes GeometricObject an abstract class. Abstract base classes (2/5) Example import java.awt.*; abstract public class GeometricObject { // instance variables  Point position; Color color; // getPosition(): return object position public Point getPosition() { return position; } // setPosition(): update object position public void setPosition(Point p) { position = p; }

  33. Indicates that an implementation of method paint() will not be supplied. Abstract base classes (3/5) Example (continued) // getColor(): return object color  public Color getColor() { return color; } // setColor(): update object color  public void setColor(Color c) { color = c; } // paint(): render the shape to graphics context g  abstract public void paint(Graphics g); }

  34. Abstract base classes (4/5) • Subclass Box import java.awt.*; public class Box extends GeometricObject { int length, height; public Box() { this(0, 0, new Point(), Color.BLACK); } . . . public void paint(Graphics g) { Point p = getPosition(); Color c = getColor(); int l = getLength(); int h = getHeight(); g.setColor(c); g.fillRect((int) p.getX(), (int) p.getY(), l, h); } }

  35. Abstract base classes (5/5) • Subclass Circle import java.awt.*; public class Circle extends GeometricObject { int radius; public Circle() { this(0, new Point(), Color.BLACK); } . . . public void paint(Graphics g) { Point p = getPosition(); Color c = getColor(); int r = getRadius(); g.setColor(c); g.fillOval((int) p.getX(), (int) p.getY(), r, r); } }

  36. Interfaces (1/5) • An interface is a template that specifies what must be in a class that implements the interface • An interface cannot specify any method implementations • All the methods of an interface are public • All the variables defined in an interface are public, final, and static • Why use an interface when an abstract class offers greater flexibility? • A class can implement more than one interface, whereas a class can extend only one superclass. • As an interface is not a class, it is not part of the class hierarchy. Hence, two unrelated classes can implement the same interface with objects of those unrelated classes having the same type – the interface their class types implements.

  37. Interfaces (2/5) • An interface for a colorable object package geometry; import java.awt.*; public interface Colorable { // getColor(): return the color of the object publicColor getColor(); // setColor(): set the color of the object public void setColor(Color c); }

  38. Interfaces (3/5) • Now the interface can be used to create classes that implement the interface • ColorablePoint import java.awt.*; public class ColorablePoint extends Point implements Colorable { // instance variable  Color color; // ColorablePoint(): default constructor public ColorablePoint() { super(); setColor(Color.blue); } . . .

  39. Interfaces (4/5) • Colorable3DPoint import java.awt.*; public class Colorable3DPoint extends ThreeDimensionalPoint implements Colorable { // instance variable  Color color; // Colorable3DPoint(): default constructor  public Colorable3DPoint() { super(); setColor(Color.blue); } . . .

  40. ColorablePoint method setColor() is invoked. Colorable3DPoint method setColor() is invoked. Interfaces (5/5) • As both ColorablePoint and Colorable3DPoint indicate they implement interface Colorable, a polymorphic code segment such as this is possible. ColorablePoint u = new ColorablePoint(); Colorable3DPoint v = new Colorable3DPoint(); Colorable w = u; w.setColor(Color.BLACK); w = v; w.setColor(Color.RED);

  41. Class Method Variable Abstract Final Static None Private Public Protected

More Related