Section 11 5 Code Reuse Through Inheritance Fundamentals

  • Slides: 9
Download presentation
Section 11. 5 Code Reuse Through Inheritance Fundamentals of Java: AP Computer Science Essentials,

Section 11. 5 Code Reuse Through Inheritance Fundamentals of Java: AP Computer Science Essentials, 4 th Edition Lambert / Osborne

Chapter 3 Code Reuse Through Inheritance 2 l All Java classes are part of

Chapter 3 Code Reuse Through Inheritance 2 l All Java classes are part of an immense hierarchy, with Object at the room. l A class can add new variables to inherited characteristics as needed. Classes can also add new methods and/or modify inherited methods. l

Code Reuse Through Inheritance (continued) l l Chapter 3 l Review of Terminology: Root:

Code Reuse Through Inheritance (continued) l l Chapter 3 l Review of Terminology: Root: top position in upside-down tree hierarchy (Object). Subclasses: extend Object (AAA). Superclass: the class immediately above another (AAA to BBB and CCC).

Code Reuse Through Inheritance (continued) l Chapter 3 l 4 Review of Terminology (cont):

Code Reuse Through Inheritance (continued) l Chapter 3 l 4 Review of Terminology (cont): Part of a class hierarchy

Code Reuse Through Inheritance (continued) l l Chapter 3 l 5 Wheel as a

Code Reuse Through Inheritance (continued) l l Chapter 3 l 5 Wheel as a Subclass of Circle: Wheel extends Circle, so it inherits properties from Circle, such as implements Shape. The variable spokes is the only one declared; all others are inherited from Circle. – – Circle variables must be declared protected. Circle’s descendents can access the variables while hiding them from other classes.

Code Reuse Through Inheritance (continued) l Chapter 3 l 6 l Detailed Explanation: A

Code Reuse Through Inheritance (continued) l Chapter 3 l 6 l Detailed Explanation: A protected method is accessible to a class’s descendents, but not any other classes in the hierarchy. The keyword super activates a constructor in Circle, and the parameter list used with super determines which constructor in Circle is called.

Code Reuse Through Inheritance (continued) l Chapter 3 l 7 Detailed Explanation (cont): The

Code Reuse Through Inheritance (continued) l Chapter 3 l 7 Detailed Explanation (cont): The keyword super can be used in methods other than constructors: – Can appear in any place with the method. – Activates the named method in the superclass (polymorphic).

Code Reuse Through Inheritance (continued) l l Chapter 3 l 8 l l Detailed

Code Reuse Through Inheritance (continued) l l Chapter 3 l 8 l l Detailed Explanation (cont): Methods that are inherited unchanged from Circle are not implemented in Wheel. Methods redefined in class Wheel when the wheel object responds differently to a message than a circle object. Subclasses can have methods not in the superclass. You cannot cast a variable to a type that conflicts with its identity.

9 Chapter 3

9 Chapter 3