Presentation is loading. Please wait.

Presentation is loading. Please wait.

An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 10 : Inheritance.

Similar presentations


Presentation on theme: "An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 10 : Inheritance."— Presentation transcript:

1 An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 10 : Inheritance

2 1May 2004NH-Chapter 10 Objectives ñAfter studying this chapter you should understand the following: ñgeneralizing classes by means of another class; ñextension, inheritance, and the subtyping relation defined by subclasses; ñmethod overloading, method overriding, and method polymorphism; ñclass extension and class composition, and their differences; ñaccessibility of public, private, protected, and package private features; ñJava’s scoping rules. ñAlso, you should be able to: ñdefine a class extending an existing class; ñimplement a class using an existing class via extension or composition.

3 2May 2004NH-Chapter 10 Abstraction and interfaces ñAn abstraction can be realized with an interface. Player InteractivePlayer «interface» Movable «interface» Weapon «interface» more abstract

4 3May 2004NH-Chapter 10 Abstraction and classes ñCan define abstraction relation between classes. ñCan specify that one class generalizes or abstracts another class. Figure OpenFigureClosedFigure RectangleCircle more abstract more concrete extends generalizes is-a

5 4May 2004NH-Chapter 10 Class extension and subtypes ñClass extension creates a subtype relation between types defined by two classes. ñType Circle is a subtype of types ClosedFigure and Figure. ñAn expression of type Circle can be written in any context requiring a ClosedFigure or Figure. Figure top; Circle soleil; (ClosedFigure)top // legal (Circle)top // legal (ClosedFigure)soleil // legal (Rectangle)soleil // Not legal

6 5May 2004NH-Chapter 10 Classes and interfaces ñA class can implement any number of interfaces. ñAn interface can extend any number of interfaces.

7 6May 2004NH-Chapter 10 Class inheritance is single inheritance ñEvery class extends exactly one other class. ñException: class Object ñThis class is at the top (or the root) of the hierarchy, and ñ Has no parent. ñEvery class is a subclass of Object.

8 7May 2004NH-Chapter 10 Class inheritance is single inheritance ñA parent class is specified with an extends clause in the class heading: public class Circle extends ClosedFigure { … ñIf a class does not specify a parent class via an extends clause, class by default extends Object.

9 8May 2004NH-Chapter 10 Class inheritance is single inheritance ñIf a class also implements an interface, the implements clause follows the extends clause. class Poison extends Potion implements Weapon { … } class Potion implements Movable { … }

10 9May 2004NH-Chapter 10 Extension and Inheritance public class ClosedFigure { private Location location; … public Location location () { return this.location; } public void moveTo (Location newLocation) { this.location = newLocation; } … }

11 10May 2004NH-Chapter 10 Class Circle extends class ClosedFigure public class Circle extends ClosedFigure { … public int radius () { … } … }

12 11May 2004NH-Chapter 10 Class Circle extends class ClosedFigure ñCircle instance inherits all features of a ClosedFigure. ñPrivate features are inherited by subclass, but not accessible from subclass. Circle circle = new Circle(10); Location loc = circle.location(); int distance = circle.radius(); this.location = null; // illegal

13 12May 2004NH-Chapter 10 Inheritance ñMechanism by which an extending class or interface automatically possesses all of the non-private features of its parent class or interface.

14 13May 2004NH-Chapter 10 Type conformance ñType Circle is a subtype of ClosedFigure. ñ Circle expression can be written wherever a ClosedFigure value is needed: Circle ring = new Circle(10); ClosedFigure enclosure; enclosure = ring; // legal. int distance = enclosure.radius(); // Not legal

15 14May 2004NH-Chapter 10 Type conformance ñCan cast from the more abstract type to the more concrete: if (enclosure instanceof Circle) int distance = ((Circle)enclosure).radius();

16 15May 2004NH-Chapter 10 Constructors and subclasses ñConstructors are not inherited: each class must define its own constructors. ñConstructor responsible for initializing instance variables in superclass and those defined in class. ñFirst thing a constructor does is invoke a constructor of its parent class. if (enclosure instanceof Circle) int distance = ((Circle)enclosure).radius();

17 16May 2004NH-Chapter 10 Constructors and subclasses ñAssuming ClosedFigure has constructor requiring no arguments. public class Circle extends ClosedFigure { private int radius; public Circle (int radius) { super(); this.radius = radius; } … }

18 17May 2004NH-Chapter 10 Constructors and subclasses  The keyword this is used in a constructor to invoke another constructor of the same class. public class Circle extends ClosedFigure { private int radius; public Circle (int radius) { super(); this.radius = radius; } public Circle () { this(1);// invoke above constructor }// with argument 1. … }

19 18May 2004NH-Chapter 10 Constructors and subclasses ñExtend Circle with a class ColoredCircle: public class ColoredCircle extends Circle { … ñConstructor for ColoredCircle invokes a Circle constructor. public class ColoredCircle extends Circle { private Color color; public ColoredCircle (int radius, Color color) { super(radius); this.color = color; } … }

20 19May 2004NH-Chapter 10 Constructors and subclasses  Constructor that neither calls a superclass constructor explicitly nor calls another constructor of same class, it implicitly begins with super(); public ColoredCircle (Color color) { this.color = color; } ñEquivalent to: public ColoredCircle (Color color) { super(); this.color = color; }

21 20May 2004NH-Chapter 10 Method overloading ñClass can contain distinct methods with same name ñ Must differ in number and/or type of parameters. public int report (int x) public int report (Object obj) public void report (int x, int y)

22 21May 2004NH-Chapter 10 Method overloading ñA class cannot contain two methods with ñsame name, and ñsame number and type of parameters. public void report (int x) public Object report (int i) // not legal

23 22May 2004NH-Chapter 10 Method overloading  Class Reporter has two methods named report : public void report (Object obj) { //1 System.out.println("The argument is an object."); } public void report (Circle circle) { //2 System.out.println("The argument is a circle."); }

24 23May 2004NH-Chapter 10 Method overloading  Assume reporter is an instance of class Reporter. Circle circle = new Circle(1); Figure figure = circle; Object object = figure; … reporter.report(circle); // invokes report with parameter Circle reporter.report(object); // invokes report with parameter Object reporter.report(figure); // invokes report with parameter Object

25 24May 2004NH-Chapter 10 Method overloading and inheritance  Suppose class Reporter inherits a report method: class Parent {… public void report (Object obj) { System.out.println("The argument is an object."); } class Reporter extends Parent {… public void report (Circle circle) { System.out.println("The argument is a circle."); }  Class Reporter has two different report methods. ñ Statement below results in “The argument is an object” Object object; reporter.report(object);

26 25May 2004NH-Chapter 10 Method overloading  overloading: class with several methods with same name. ñMethods are reasonably overloaded if have same function but offer alternative ways of providing arguments. ñRule : never overload a method by changing the type of a parameter to a subtype or supertype.

27 26May 2004NH-Chapter 10 Method overriding ñOverriding: class redefines implementation of an inherited method.  All classes inherits method equals which is defined for class Object, and every class is a subclass of Object.

28 27May 2004NH-Chapter 10 Method overriding  Redefine equals in class Circle so that two Circles with same radius are considered equal, regardless of their locations: public class Circle extends ClosedFigure { … public boolean equals (Object c) { if (c instanceof Circle) return this.radius() == ((Circle)c).radius(); else return false; } … }

29 28May 2004NH-Chapter 10 Method overriding Object +boolean equals(Object obj) {… } Circle +boolean equals(Object obj) {… } Rectangle +boolean equals(Object obj) {… } ClosedFigure defines equals inherits equals as redefine equals implemented in parent

30 29May 2004NH-Chapter 10 Polymorphism  Which equals method is executed at * depends on the object figure1 references when the statement is reached. BasicFileReader in = new BasicFileReader(); ClosedFigure figure1; ClosedFigure figure2; int n; in.readInt(); n = in.lastInt(); if (n == 0) { figure1 = new Circle(); figure2 = new Circle(); } else { figure1 = new Rectangle(); figure2 = new Rectangle(); } boolean b = figure1.equals(figure2); // *

31 30May 2004NH-Chapter 10 Accessing overridden implementation  A class that overrides a method can call its parent’s implementation with key word super.  Assume class ClosedFigure defines methods moveTo and location : public void moveTo (Location newLocation) Move this ClosedFigure to the specified Location. public Location location () The location of this ClosedFigure.

32 31May 2004NH-Chapter 10 Accessing overridden implementation ñSuppose want to equip Circle with method to reverse most recent move: public void moveBack () Move this Circle back to where it was before the most recent move.

33 32May 2004NH-Chapter 10 Accessing overridden implementation  We must override the inherited moveTo method, and remember the location we are moving from. public class Circle extends ClosedFigure { … private Location previousLocation … public void moveTo (Location newLocation) { this.previousLocation = this.location(); super.moveTo(newLocation); } … }

34 33May 2004NH-Chapter 10 Overriding and Polymorphism  overriding: providing an alternative implementation of an inherited method.  polymorphism: dynamic behavior by which algorithm performed by invoked method is determined at run-time by class of object executing method.

35 34May 2004NH-Chapter 10 Overloading and Overriding ñSuppose a programmer writes public class Circle { … public boolean equals (Circle c) { return this.radius() == c.radius(); } … }  This definition overloads the equals method inherited from Object, but does not override it.

36 35May 2004NH-Chapter 10 Overloading and Overriding ñGiven: Circle circle1 = new Circle(1); Circle circle2 = new Circle(1); Object object2 = circle2; circle1.equals(circle2) // returns true circle1.equals(object2) // returns false ñThe first expression invokes method defined in Circle while second expression invokes inherited method.  circle1, and object2 are two different Object instances, then inherited method equals returns false.

37 36May 2004NH-Chapter 10 Overloading and Overriding  Suppose class Parent defines a method report, class Parent {… ¹public void report (Object obj) { System.out.println("Parent.report(Object)"); }

38 37May 2004NH-Chapter 10 Overloading and Overriding ñMethod report is overridden and overloaded in subclass Child class Child extends Parent {… public void report (Object obj) { System.out.println("Child.report(Object)"); } public void report (Circle obj) { System.out.println("Child.report(Circle)"); }  Last statement produces: “ Child.report(Object)” Child child = new Child(); Parent parent = child; Circle circle = new Circle(1); parent.report(circle);

39 38May 2004NH-Chapter 10 Overriding and contracts ñType defined by a class is also a subtype of type defined by its parent superclass. ñA subclass instance can be used where a superclass instance is expected. ñinvert can be invoked with a Circle as argument. ñA subclass is obligated to respect the contract offered by its parent superclass. public void invert (ClosedFigure f)

40 39May 2004NH-Chapter 10 Overriding and contracts ñRules regarding precondition and postconditions and method overriding: ñWhen overriding a method, preconditions can be weakened but cannot be strengthened. ñWhen overriding a method, postconditions can be strengthened but cannot be weakened.

41 40May 2004NH-Chapter 10 Overriding and contracts Class ClosedFigure public void fill (Color c) Paint this ClosedFigure with the specified Color. ensure: this.backgroundColor().equals(c) public class MonochromeFigure extends ClosedFigure ñA MonochromeFigure can be supplied wherever a ClosedFigure is required. ñMonochromeFigure  can override method fill, ñbound to the contract as specified in ClosedFigure.

42 41May 2004NH-Chapter 10 Overriding and contracts  MonochromeFigure overrides fill : /** * Paint this MonochromeFigure black or white. * * @requirec.equals(Color.white) || c.equals(Color.black) */ public void fill (Color c) { assert c.equals(Color.white) || c.equals(Color.black); … ñPrecondition has been strengthened, method no longer respects inherited contract. CloseFigure fig = new MonochromeFigure(); fig.fill(Color.gray); // it will fail.

43 42May 2004NH-Chapter 10 Overriding and contracts  MonochromeFigure method fill treats any non-while color as black. public void fill (Color c) Paint this MonochromeFigure white or black. ensure: if c.equals(Color.white) this.backgroundColor().equals(c) else this.backgroundColor().equals(Color.black) ñPostcondition is weakened. Causes problems for ClosedFigure client expecting postconditions given in ClosedFigure to be met.

44 43May 2004NH-Chapter 10 private features access ñprivate features are accessible from within the defined class. public class Circle { private int r; public Circle (int radius) { this.r = radius; } public boolean equals (Object obj) { if (obj instanceof Circle) ¹return r == ((Circle)obj).r; //1 else return false; } public int radius() { return r; }  At 1, private instance variable r of argument obj is accessed.

45 44May 2004NH-Chapter 10 private features access ñconsider extending Circle with a class ColoredCircle: public class ColoredCircle extends Circle { private Color c; public ColoredCircle (int radius, Color color) { super(radius); c = color; } public boolean equals (Object obj) { if (obj instanceof ColoredCircle) return r == ((Circle)obj).r && //not legal access to r c == ((ColoredCircle)obj).c; else return false; } public Color color () { return c; }

46 45May 2004NH-Chapter 10 private features access  Neither of the references to r in the equals method is legal.  r is private to Circle and can be accessed only in that class.  ColoredCircle does not inherit Circle private component r, thus r cannot be directly accessed in ColoredCircle. ñEven casting an object to a Circle, instance variable r can be accessed only from within definition of class Circle.

47 46May 2004NH-Chapter 10 private features access ñA ColoredCircle is-a Circle and cannot access r ColoredCircle +int radius() +Color color() -int r Circle obj -Color c

48 47May 2004NH-Chapter 10 private features access  The method equals can be written legally using query radius : public boolean equals (Object obj) { if (obj instanceof ColoredCircle) return this.radius() == ((Circle)obj).radius() && c == ((ColoredCircle)obj).c; else return false; }

49 48May 2004NH-Chapter 10 private features access ñA class not labeled public is package private and can be accessed only from within its own package. ñ If the class is not visible outside its package, neither are any of its features. ñAccess to features of a nonpublic class, even if the features are labeled public, is limited to package containing class definition.

50 49May 2004NH-Chapter 10 protected features access ñsubclass inherits protected features, and these features are accessible in the subclass. public class Circle { protected int r; … }  The references to r in subclasses are legal.

51 50May 2004NH-Chapter 10 protected features access ñColoredCircle is a subclass of Circle, and defining r protected makes the code below legal: public class ColoredCircle extends Circle { private Color c; … public boolean equals (Object obj) { if (obj instanceof ColoredCircle) { ColoredCircle other = (ColoredCircle)obj; return r == other.r && c == other.c; } else return false; } … }

52 51May 2004NH-Chapter 10 protected features access ñA feature declared protected is accessible from anywhere in package containing the class in which the feature is defined.  Thus protected variable r defined in Circle can be invoked from anywhere in the package containing Circle. ñShould consider a protected feature to be part of contract a class offers to its subclasses, and not a feature to be accessed by other clients.

53 52May 2004NH-Chapter 10 protected features access  Instances of class Child and Grandchild inherit, and can access, feature f. package p1; public class Parent { protected int f; … } ña protected feature is inherited.

54 53May 2004NH-Chapter 10 protected features access  feature f in class Parent is accessible from anywhere in the package p1.  Methods clearChildF and clearGrandchildF can appear in any class in the package p1. public void clearChildF (Child c) { c.f = 0; } public void clearGrandchildF (Grandchild g) { g.f = 0; }

55 54May 2004NH-Chapter 10 protected features access  protected feature of a class is accessible in any superclasses “through which” feature was inherited.  Grandchild inherits feature f “through Child,” method clearGrandchildF can also appear in class Child.  Method clearChildF cannot appear in Grandchild, unless Grandchild happens to be in package p1.

56 55May 2004NH-Chapter 10 Restricted or package private features access  Feature not declared public, protected, or private is by default package private. ñA package private feature is accessible anywhere in package containing class in which feature is defined. ñPackage private feature ñpublic feature inside package, ñprivate feature outside the package.

57 56May 2004NH-Chapter 10 Restricted or package private features access ñConsider classes Explorer and Room from the maze game. ñSuppose Explorer must know which room is in, and Room must know its contents.

58 57May 2004NH-Chapter 10 Restricted or package private features access  Explorer has a command move, ñ Explorer may leave one Room and enter another.  Command move must inform a Room that Explorer is entering or leaving. ñEquip a Room with methods for adding and removing an Explorer:

59 58May 2004NH-Chapter 10 Restricted or package private features access Class Room: void add (Explorer e) specified Explorer has entered this Room, and should be added to this Room’s contents. invoked by an Explorer when entering Room. void remove (Explorer e) specified Explorer has left this Room, and should be removed from its contents; invoked by an Explorer when leaving this Room. ñHow should we label these Room methods? ñNot private, as an Explorer must invoke them. ñNot public, only an Explorer must invoke them. ñMake them package private ñClasses Explorer and Room are tightly coupled.

60 59May 2004NH-Chapter 10 Nested classes ñNested class: class member of another class. ñA nested class can be defined ñdirectly in a containing class, called member class; ñin the body of a method or constructor.

61 60May 2004NH-Chapter 10 Nested classes ñMember classes can be public, private, protected, or package private. ñA member class can also be static, in which case it is associated with the containing class ñA non-static member class is associated with an instance of the containing class.

62 61May 2004NH-Chapter 10 Nested classes ñA class defined in body of a method or constructor ñlocal class: named class, ñanonymous class : unnamed class. ñlocal class: visible only inside method where defined.

63 62May 2004NH-Chapter 10 Inner classes ñInner class: a nested class that is not a static member class. public class Outer { … private class MyInner { … } // end of class MyInner … } // end of class Outer ñClass MyInner is a member of the top level class Outer. ñMyInner is private, accessible only from inside Outer.

64 63May 2004NH-Chapter 10 Inner classes feature access ñFeature access is determined only by the top level class. public class Outer { private int size; … private class Inner { private Inner next; … } // end of class Inner … } // end of class Outer  Private Outer variable size is visible in class Inner.  Private variable next of Inner can be accessed in class Outer.

65 64May 2004NH-Chapter 10 Inner classes feature access ñA nonstatic member class is a member of some instance of containing class. ñ Each inner class instance is associated with an instance of containing class  From inside Inner, expression Outer.this refers to Outer instance of which Inner class is a member. Outer int size0 class Inner Outer.Inner Outer.this instanceof

66 65May 2004NH-Chapter 10 Inner classes feature access ñClass Inner can contain a method like this: ñIt can be rewritten as: private void evaporate () { size = size - 1; // Outer’s instance variable … } private void evaporate () { Outer.this.size = Outer.this. size - 1; … }

67 66May 2004NH-Chapter 10 Inner classes feature access ñA not private inner class is accessible from outside the containing top level class. ñName of type defined by inner class is formed by prefixing outer class name to inner class name. public class Outer { … public class Inner { … } // end of class Inner … } // end of class Outer ñType defined by inner class is Outer.Inner: Outer bag = new Outer(); Outer.Inner node = bag.new Inner();

68 67May 2004NH-Chapter 10 Scope rules for method variables ñA method variable is accessible from its definition to the end of the compound statement (or method body) in which it is defined. ñA parameter is accessible anywhere in the method body. ñA method can define several method variables with the same name as long as their scopes do not overlap.

69 68May 2004NH-Chapter 10 Summary ñExamined abstraction as defined by a hierarchy of classes. ñEvery class (except Object) extends exactly one parent superclass; ñtype defined by a (sub)class is a subtype of type defined by its superclass. ñExtends relation between a class and its parent superclass is same as implements relation between a class and an interface.

70 69May 2004NH-Chapter 10 Summary ñClass contains an implementation, including ñinstance variables, ñconstructors, ñmethod bodies. ñWhen class B extends class A, it inherits B’s features along with implementation. ñExtending class can, add to or modify inherited implementation. ñClass does not inherit its parent’s constructors, ñWhen a class is instantiated, each ancestor constructor is executed, beginning with Object and ending with a constructor of the instantiated class.

71 70May 2004NH-Chapter 10 Summary ñA subclass can override an inherited method. ñA subclass must meet contract of parent’s methods. ñAn overridden method can: ñweaken preconditions but not strengthen them. ñstrengthen postconditions but not weaken them.

72 71May 2004NH-Chapter 10 Summary ñOverloading means supplying a class with several distinct methods having the same name. ñOverloaded methods are distinguished by their parameter lists. ñOverloading is resolved by the compiler according to the static types of the argument expressions that appear in a method invocation. ñOverriding means giving an inherited method a different implementation than it has in the parent superclass. ñAt run time, implementation executed by an overridden method depends on the class of the object that actually performs the method. (Polymorphism)

73 72May 2004NH-Chapter 10 Summary ñClass features, (instance variables, methods), can be declared public, private, protected, or package private. ñPublic features constitute the specification of the class, and define the view offered to the class’s clients. ñPrivate, protected, and package private features should be considered part of the implementation. ñPrivate features are accessible only in the class definition. ñProtected features are inherited by subclasses, and are part of the contract a class offers its subclasses. ñUnfortunately, a protected feature is also accessible anywhere in the package containing the class defining the feature. ñPackage private feature is accessible in the package containing the class defining the feature.

74 73May 2004NH-Chapter 10 Summary ñScoping rules for method variables are simple. ñA method variable is accessible from its definition to the end of the compound statement (or method body) in which it is defined. ñA parameter is accessible anywhere in the method body. ñA method can define several method variables with the same name as long as their scopes do not overlap.


Download ppt "An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 10 : Inheritance."

Similar presentations


Ads by Google