Chapter 8 Inheritance Part 1 Inheritance Inheritance is

  • Slides: 28
Download presentation
Chapter 8 Inheritance Part 1

Chapter 8 Inheritance Part 1

Inheritance • Inheritance is a fundamental object-oriented design technique used to create and organize

Inheritance • Inheritance is a fundamental object-oriented design technique used to create and organize reusable classes • Chapter 8 focuses on: § § § § § deriving new classes from existing classes the protected modifier creating class hierarchies abstract classes indirect visibility of inherited members designing for inheritance the GUI component class hierarchy extending listener adapter classes the Timer class © 2004 Pearson Addison-Wesley. All rights reserved 2

Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance and Visibility Designing for Inheritance and

Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance and Visibility Designing for Inheritance and GUIs The Timer Class © 2004 Pearson Addison-Wesley. All rights reserved 3

Inheritance • Inheritance allows a software developer to derive a new class from an

Inheritance • Inheritance allows a software developer to derive a new class from an existing one • The existing class is called the parent class, or superclass, or base class • The derived class is called child class or subclass • As the name implies, the child inherits characteristics of the parent • That is, the child class inherits the methods and data defined by the parent class 4

Inheritance • Inheritance relationships are shown in a UML class diagram using a solid

Inheritance • Inheritance relationships are shown in a UML class diagram using a solid arrow with an unfilled triangular arrowhead pointing to the parent class Vehicle Car Please note: a ‘dashed’ arrow with same triangle means ‘realizes’ in UML. This is quite different! There are not many of these symbols, but you definitely need to learn the ones we see. • Proper inheritance creates an is-a relationship, meaning the child is a more specific version of the parent 5

Inheritance • A programmer can tailor a derived class as needed by adding new

Inheritance • A programmer can tailor a derived class as needed by adding new variables or methods, or by modifying the inherited ones • Software reuse is a fundamental benefit of inheritance • By using existing software components to create new ones, we capitalize on all the effort that went into the design, implementation, and testing of the existing software • Component-based software development is HUGE in the industry today! © 2004 Pearson Addison-Wesley. All rights reserved 6

Deriving Subclasses • In Java, we use the reserved word extends to establish an

Deriving Subclasses • In Java, we use the reserved word extends to establish an inheritance relationship derived class (child class) class Car extends Vehicle { // class contents } base class (parent class) • Let’s look at some code… 7

//********************************** // Words. java Author: Lewis/Loftus // // Demonstrates the use of an inherited

//********************************** // Words. java Author: Lewis/Loftus // // Demonstrates the use of an inherited method. //********************************** public class Words { //--------------------------------// Instantiates a derived class and invokes its inherited and local methods. //--------------------------------public static void main (String[] args) { Dictionary webster = new Dictionary(); System. out. println ("Number of pages: " + webster. get. Pages()); System. out. println ("Number of definitions: " + webster. get. Definitions()); System. out. println ("Definitions per page: " + webster. compute. Ratio()); } // end main() } // end Words Looks simple enough. Creating an object webster of type Dictionary. Then we are executing a few of webster’s methods (from the class…) So, we need to see what the Dictionary class looks like, right? © 2004 Pearson Addison-Wesley. All rights reserved 8

//********************************** // Dictionary. java Author: Lewis/Loftus // Represents a dictionary, which is a book.

//********************************** // Dictionary. java Author: Lewis/Loftus // Represents a dictionary, which is a book. Used to demonstrate // inheritance. //********************************** public class Dictionary extends Book But we note that Dictionary ‘inherits’ Book! { // Parent (super, or base) class is Book. Dictionary is a derived // class, and our object, webster, is an object of the derived class // Dictionary. private int definitions = 52500; //--------------------------------// Prints a message using both local and inherited values. //--------------------------------public double compute. Ratio () { return definitions/pages; Note methods here in } // end compute. Ration() // Definitions mutator. ============ public void set. Definitions (int num. Definitions) { definitions = num. Definitions; } // end mutator // Definitions accessor. ============= public int get. Definitions () { return definitions; } // end accessor } // end Dictionary © 2004 Pearson Addison-Wesley. All rights reserved Dictionary (usable by webster, of course. Again, mutator and accessor methods are quite common. Now, onto the base class! 9

//********************************** // Book. java Author: Lewis/Loftus // // Represents a book. Used as the

//********************************** // Book. java Author: Lewis/Loftus // // Represents a book. Used as the parent of a derived class to demonstrate inheritance. //********************************** public class Book { protected int pages = 1500; // instance variable for objects. // Pages mutator. public void set. Pages (int num. Pages) { pages = num. Pages; } // end set. Pages // Pages accessor. public int get. Pages () { return pages; } // end get. Pages() Standard mutator and accessor (get and set methods…) } // end Book Let’s go back to the main one… © 2004 Pearson Addison-Wesley. All rights reserved 10

//********************************** // Words. java Author: Lewis/Loftus // // Demonstrates the use of an inherited

//********************************** // Words. java Author: Lewis/Loftus // // Demonstrates the use of an inherited method. //********************************** public class Words { //--------------------------------// Instantiates a derived class and invokes its inherited and local methods. Where from? //--------------------------------NOT in public static void main (String[] args) Dictionary!! { Dictionary webster = new Dictionary(); System. out. println ("Number of pages: " + webster. get. Pages()); System. out. println ("Number of definitions: " + webster. get. Definitions()); System. out. println ("Definitions per page: " + webster. compute. Ratio()); } // end main() } // end Words We KNOW where these are from. Looks simple enough. Creating an object webster of type Dictionary. Then we are executing a few of webster’s methods (from the class…) So, we need to see what the Dictionary class looks like, right? © 2004 Pearson Addison-Wesley. All rights reserved 11

Book Dictionary Here is our UML diagram showing inheritance. Dictionary is a derived class

Book Dictionary Here is our UML diagram showing inheritance. Dictionary is a derived class from Book, the base class. Webster is an object of type Dictionary. Objects are not shown in a class diagram, as above. Of course, all attributes and methods in Book are inherited by Dictionary. Thus any object of type Dictionary has access to all methods and attributes of all. © 2004 Pearson Addison-Wesley. All rights reserved 12

The protected Modifier • Visibility modifiers affect the way that class members can be

The protected Modifier • Visibility modifiers affect the way that class members can be used in a child class • Variables and methods declared with private visibility cannot be referenced by name in a child class • They can be referenced in the child class if they are declared with public visibility -- but public variables violate the principle of encapsulation!!! • There is a third visibility modifier that helps in inheritance situations: protected 13

The protected Modifier • The protected modifier allows a child class to reference a

The protected Modifier • The protected modifier allows a child class to reference a variable or method directly in the child class • It provides more encapsulation than public visibility, but is not as tightly encapsulated as private visibility • A protected variable is visible to any class in the same package as the parent class • The details of all Java modifiers are discussed in Appendix E • Protected variables and methods can be shown with a # symbol preceding them in UML diagrams 14

Final Class Diagram for Words Book “Inherits from” or A Dictionary ‘is_a’ Book. #

Final Class Diagram for Words Book “Inherits from” or A Dictionary ‘is_a’ Book. # pages : int + page. Message() : void Words Dictionary - definitions : int + main (args : String[]) : void + definition. Message() : void “uses” or “depends on” (means likely that it sends messages and requires some services…. ) (Objects of type Dictionary inherit page. Message(), and pages (attribute), etc. from base class. ) © 2004 Pearson Addison-Wesley. All rights reserved 15

The super Reference • Constructors are not inherited, even though they have public visibility

The super Reference • Constructors are not inherited, even though they have public visibility • Yet we often want to use the parent's constructor to set up the "parent's part" of the object • The super reference can be used to refer to the parent class, and often is used to invoke the parent's constructor • OK. So, let’s look further into inheritance to some VERY important principles. 16

// Words 2. java Author: Lewis/Loftus // Demonstrates the use of the super reference.

// Words 2. java Author: Lewis/Loftus // Demonstrates the use of the super reference. public class Words 2 { // Instantiates a derived class and invokes its inherited and local methods. Creating an object public static void main (String[] args) of type Dictionary 2 { Dictionary 2 webster = new Dictionary 2 (1500, 52500); Constructor needs two arguments. System. out. println ("Number of pages: " + webster. get. Pages()); System. out. println ("Number of definitions: " + webster. get. Definitions()); System. out. println ("Definitions per page: " + webster. compute. Ratio()); } // end main() } // end Words 2 © 2004 Pearson Addison-Wesley. All rights reserved So, let’s look to see what Dictionary 2 looks like…. 17

// Dictionary 2. java Author: Lewis/Loftus // Represents a dictionary, which is a book.

// Dictionary 2. java Author: Lewis/Loftus // Represents a dictionary, which is a book. Used to demonstrate the use of the super reference. public class Dictionary 2 extends Book 2 We know this means inheritance from Book 2. { private int definitions; // Constructor: Sets up the dictionary with the specified number of pages and definitions. public Dictionary 2 (int num. Pages, int num. Definitions) { super(num. Pages); This means that the argument passed to the constructor is used to initialize the attribute (variable) num. Pages in the base class! What is happening is that this method call passes the argument num. Pages to the Constructor of the base class to initialize ‘pages’ in the base class. definitions = num. Definitions; This is used to initialize the instance variable, definitions. } // end Constructor. // Prints a message using both local and inherited values. public double compute. Ratio () { return definitions/pages; uses attributes of object (instance variable definitions) divided by the attribute of the base class (pages) which was inherited. } // end compute. Ratio() // Definitions mutator. public void set. Definitions (int num. Definitions) { definitions = num. Definitions; used to set instance variable. } // end set. Definitions() etc. } // end Dictionary 2 © 2004 Pearson Addison-Wesley. All rights reserved 18

// Book 2. java Author: Lewis/Loftus // Represents a book. Used as the parent

// Book 2. java Author: Lewis/Loftus // Represents a book. Used as the parent of a derived class to // demonstrate inheritance and the use of the super reference. //********************************** public class Book 2 { protected int pages; Note ‘protected’ //--------------------------------// Constructor: Sets up the book with the specified number of pages. //--------------------------------public Book 2 (int num. Pages) { pages = num. Pages; } // end Constructor // Pages mutator. --------------------public void set. Pages (int num. Pages) { pages = num. Pages; } // end set. Pages() // Pages accessor. -------------------public int get. Pages () { return pages; } // end get. Pages() 2004 Pearson Addison-Wesley. All rights reserved } end©Book 2 Nothing special. Constructor needs an int. Protected means derived class (and hence objects of derived class) can access the attribute: pages. 19

The super Reference • A child’s constructor is responsible for calling the parent’s constructor

The super Reference • A child’s constructor is responsible for calling the parent’s constructor • The first line of a child’s constructor should use the super reference to call the parent’s constructor • The super reference can also be used to reference other variables and methods defined in the parent’s class • This can be useful when there is a conflict… that is, a derived class and the base class have the same method name. Clearly derived class’s method would be inherited by an object, unless the object needs the parent’s version. © 2004 Pearson Addison-Wesley. All rights reserved 20

Multiple Inheritance • Java supports single inheritance, meaning that a derived class can have

Multiple Inheritance • Java supports single inheritance, meaning that a derived class can have only one parent class • Multiple inheritance allows a class to be derived from two or more classes, inheriting the members of all parents • Collisions, such as the same variable name in two parents, have to be resolved • Java does not support multiple inheritance • In most cases, the use of interfaces gives us aspects of multiple inheritance without the overhead § In actuality, the simulate multiple inheritance, you might use a combination of regular inheritance plus an interface. © 2004 Pearson Addison-Wesley. All rights reserved 21

Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance and Visibility Designing for Inheritance and

Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance and Visibility Designing for Inheritance and GUIs The Timer Class © 2004 Pearson Addison-Wesley. All rights reserved 22

Overriding Methods (not Overloading!) • A child class can override the definition of an

Overriding Methods (not Overloading!) • A child class can override the definition of an inherited method in favor of its own • The new method must have the same signature as the parent's method, but can have a different body • The type of the object executing the method determines which version of the method is invoked • This goes to polymorphism too. Very important! Next chapter. 23

//********************************** // Messages. java Author: Lewis/Loftus // Demonstrates the use of an overridden method.

//********************************** // Messages. java Author: Lewis/Loftus // Demonstrates the use of an overridden method. public class Messages { //--------------------------------// Creates two objects and invokes the message method in each. //--------------------------------public static void main (String[] args) { Thought parked = new Thought(); creates object of type Thought (a base class…) Advice dates = new Advice(); creates object of type Advice, a derived class of Thought. parked. message(); Goes to Thought…Prints out simple message. Method of base class invoked directly via inheritance. dates. message(); // overridden Goes to Advice (object of class derived from base class, Thought. Prints out message from Advice and THEN prints out message from Thought invoked via the super method. } // end main() } // end Messages © 2004 Pearson Addison-Wesley. All rights reserved 24

//********************************** // Thought. java Author: Lewis/Loftus // // Represents a stray thought. Used as

//********************************** // Thought. java Author: Lewis/Loftus // // Represents a stray thought. Used as the parent of a derived // class to demonstrate the use of an overridden method. //********************************** public class Thought This turns out to be a base class. { //--------------------------------// Prints a message. //--------------------------------public void message() { System. out. println ("I feel like I'm diagonally parked in a " + "parallel universe. "); System. out. println(); } // end message() } // end Thought © 2004 Pearson Addison-Wesley. All rights reserved 25

//********************************** /// Advice. java Author: Lewis/Loftus /// *// Represents some thoughtful advice. Used to

//********************************** /// Advice. java Author: Lewis/Loftus /// *// Represents some thoughtful advice. Used to demonstrate the use *// of an overridden method. *//********************************** * *public class Advice extends Thought { * //--------------------------------* // Prints a message. This method overrides the parent's version. * //--------------------------------* public void message() * { * System. out. println ("Warning: Dates in calendar are closer " + "than they appear. "); * * * System. out. println(); * super. message(); // explicitly invokes the parent's version * } // end message() *} // end Advice * © 2004 Pearson Addison-Wesley. All rights reserved * 26

Overriding • A method in the parent class can be invoked explicitly using the

Overriding • A method in the parent class can be invoked explicitly using the super reference • If a method is declared with the final modifier, it cannot be overridden • The concept of overriding can be applied to data too and is called shadowing variables • Shadowing variables should be avoided because it tends to cause unnecessarily confusing code © 2004 Pearson Addison-Wesley. All rights reserved 27

Overloading vs. Overriding • Overloading deals with multiple methods with the same name in

Overloading vs. Overriding • Overloading deals with multiple methods with the same name in the same class, but with different signatures • Overriding deals with two methods, one in a parent class and one in a child class, that have the same signature • Overloading lets you define a similar operation in different ways for different parameters • Overriding lets you define a similar operation in different ways for different object types 28