Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Chapter 7 Inheritance Chapter 7 Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Principles of OOP Chapter 7 OOP - Object-Oriented Programming Principles discussed in previous chapters: » Information Hiding » Encapsulation » Polymorphism In this chapter » Inheritance Java: an Introduction to Computer Science & Programming - Walter Savitch 2 Why OOP? Chapter 7 To try to deal with the complexity of programs To apply principles of abstraction to simplify the tasks of writing, testing, maintaining and understanding complex programs To increase code reuse » to reuse classes developed for one application in other applications instead of writing new programs from scratch ("Why reinvent the wheel?") Inheritance is a major technique for realizing these objectives Java: an Introduction to Computer Science & Programming - Walter Savitch 3 Inheritance Overview Inheritance allows you to define a very general class then later define more specialized classes by adding new detail » the general class is called the base or parent class The specialized classes inherit all the properties of the general class » specialized classes are derived from the base class » they are called derived or child classes After the general class is developed you only have to write the "difference" or "specialization" code for each derived class A class hierarchy: classes can be derived from derived classes (child classes can be parent classes) » any class higher in the hierarchy is an ancestor class » any class lower in the hierarchy is a descendent class Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 4 An Example of Inheritance: a Person Class The base class: Display 7.1 Constructors: » a default constructor » one that initializes the name attribute (instance variable) Accessor methods: » setName to change the value of the name attribute » getName to read the value of the name attribute » writeOutput to display the value of the name attribute One other class method: » sameName to compare the values of the name attributes for objects of the class Note: the methods are public and the name attribute private Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 5 A Person Base Class Display 7.1 Chapter 6 public class Person { private String name; public Person() { name = "No name yet."; } public Person(String initialName) { name = initialName; } public void setName(String newName) { name = newName; } public String getName() { return name; } public void writeOutput() { System.out.println("Name: " + name); } public boolean sameName(Person otherPerson) { return (this.name.equalsIgnoreCase(otherPerson.name)); } } Java: an Introduction to Computer Science & Programming - Walter Savitch 6 Derived Classes: a Class Hierarchy Person Student Undergraduate MastersDegree Chapter 7 Employee Graduate PhD Faculty Staff NonDegree The base class can be used to implement specialized classes » For example: student, employee, faculty, and staff Classes can be derived from the classes derived from the base class, etc., resulting in a class hierarchy Java: an Introduction to Computer Science & Programming - Walter Savitch 7 Example of Adding Constructor in a Derived Class: Student public class Student extends Person { private int studentNumber; public Student() Keyword extends in { first line super(); » creates derived studentNumber = 0; class from base } class The first few lines of … » this is inheritance Student class (Display 7.3): Two new constructors (one on next slide) » default initializes attribute studentNumber to 0 super must be first action in a constructor definition » Included automatically by Java if it is not there » super()calls the parent default constructor Chapter 6 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 8 Example of Adding Constructor in a Derived Class: Student Passes parameter newName to constructor of parent class Uses second parameter to initialize instance variable that is not in parent class. public class Student extends Person { . . . public Student(String newName, int newStudentNumber) { super(newName); studentNumber = newStudentNumber; } . . . More lines of Student class (Display 7.3): Chapter 6 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 9 More about Constructors in a Derived Class Constructors can call other constructors Use super to invoke a constructor in parent class » as shown on the previous slide Use this to invoke a constructor within the class Chapter 7 » shown on the next slide Whichever is used must be the first action taken by the constructor Only one of them can be first, so if you want to invoke both: » Use a call with this to call a constructor with super Java: an Introduction to Computer Science & Programming - Walter Savitch 10 Example of a constructor using this Student class has a constructor with two parameters: String for the name attribute and int for the studentNumber attribute public Student(String newName, int newStudentNumber) { super(newName); studentNumber = newStudentNumber; } Another constructor within Student takes just a String argument and initializes the studentNumber attribute to a value of 0: » calls the constructor with two arguments, initialName (String) and 0 (int), within the same class public Student(String initialName) { this(initialName, 0); } Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 11 Example of Adding an Attribute in a Derived Class: Student A line from the Student class: private int studentNumber; Chapter 6 7 Note that an attribute for the student number has been added » Student has this attribute in addition to name, which is inherited from Person Java: an Introduction to Computer Science & Programming - Walter Savitch 12 Example of Overriding a Method in a Derived Class: Student Both parent and derived classes have a writeOutput method Both methods have the same parameters (none) » they have the same signature The method from the derived class overrides (replaces) the parent's It will not override the parent if the parameters are different (since they would have different signatures) This is overriding, not overloading public void writeOutput() { System.out.println("Name: " + getName()); System.out.println("Student Number : " studentNumber); } Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 13 public class Student extends Person { private int studentNumber; Display 7.3 A Derived Class (1/2) public Student() { super(); studentNumber = 0;//Indicating no number yet } public Student(String initialName, int initialStudentNumber) { super(initialName); studentNumber = initialStudentNumber; } public void reset(String newName, int newStudentNumber) { setName(newName); studentNumber = newStudentNumber; } public int getStudentNumber() { return studentNumber; } Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 14 public void setStudentNumber(int newStudentNumber) { studentNumber = newStudentNumber; Display 7.3 } A Derived Class (2/2) public void writeOutput() { System.out.println("Name: " + getName()); System.out.println("Student Number : " + studentNumber); } public boolean equals(Student otherStudent) { return (this.sameName(otherStudent) && (this.studentNumber == otherStudent.studentNumber)); } public String toString() { return("Name: " + getName() + "\nStudent number: " + Integer.toString(studentNumber)); } /********************** *Demonstrates toString. **********************/ public static void main(String[] args) { Student s = new Student("Jane Doe", 3); String stringVersion = s.toString(); System.out.println(stringVersion); System.out.println(s.toString()); } } Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 15 Display 7.4 Demonstrating Inheritance public class InheritanceDemo { public static void main(String[] args) { Student s = new Student(); s.setName("Warren Peace"); s.setStudentNumber(2001); s.writeOutput(); } } Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 16 Execution Result of InheritanceDemo.java Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 17 Call to an Overridden Method Use super to call a method in the parent class that was overridden (redefined) in the derived class Example: Student redefined the method writeOutput of its parent class, Person Could use super.writeOutput() to invoke the overridden (parent) method public void writeOutput() { super.writeOutput(); System.out.println("Student Number : " studentNumber); } Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 18 Overriding Verses Overloading Overriding Same method name Same method name Same signature One method in ancestor, one in descendant Different signature Both methods can be in same class Chapter 7 Overloading Java: an Introduction to Computer Science & Programming - Walter Savitch 19 The final Modifier Chapter 7 Specifies that a method definition cannot be overridden with a new definition in a derived class Example: public final void specialMethod() { . . . Used in specification of some methods in standard libraries Allows the compiler to generate more efficient code Can also declare an entire class to be final, which means it cannot be used as a base class to derive another class Java: an Introduction to Computer Science & Programming - Walter Savitch 20 private & public Instance Variables and Methods Chapter 7 private instance variables from the parent class are not available by name in derived classes » "Information Hiding" says they should not be » use accessor methods to change them, e.g. reset for a Student object to change the name attribute private methods are not inherited! » use public to allow methods to be inherited » only helper methods should be declared private Java: an Introduction to Computer Science & Programming - Walter Savitch 21 What is the "Type" of a Derived class? Chapter 7 Derived classes have more than one type Of course they have the type of the derived class (the class they define) They also have the type of every ancestor class » all the way to the top of the class hierarchy All classes derive from the original, predefined class Object Object is called the Eve class since it is the original class for all other classes Java: an Introduction to Computer Science & Programming - Walter Savitch 22 Assignment Compatibility Can assign an object of a derived class to a variable of any ancestor type Person josephine; Employee boss = new Employee(); josephine = boss; OK Can not assign an object of an ancestor class to a variable of a derived class type Person josephine = new Person(); Employee boss; boss = josephine; Not allowed Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch Person Employee Person is the parent class of Employee in this example. 23 Display 7.5 A Derived Class of a Derived Class (1/2) public class Undergraduate extends Student { private int level;//1 for freshman, 2 for sophomore, etc. public Undergraduate() { super(); level = 1; } public Undergraduate(String initialName, int initialStudentNumber, int initialLevel) { super(initialName, initialStudentNumber); level = initialLevel; } public void reset(String newName, int newStudentNumber, int newLevel) { reset(newName, newStudentNumber); level = newLevel; } public int getLevel() { return level; } Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 24 Display 7.5 A Derived Class of a Derived Class (2/2) public void setLevel(int newLevel) { level = newLevel; } public void writeOutput() { super.writeOutput(); System.out.println("Student Level: " + level); } public boolean equals(Undergraduate otherUndergraduate) { return (super.equals(otherUndergraduate) && (this.level == otherUndergraduate.level)); } } Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 25 public class UndergraduateDemo UndergraduateDemo Class { public static void main(String[] args) { Undergraduate ug1 = new Undergraduate("James Bond", 007, 1); ug1.writeOutput(); ug1.reset("Sam Spade", 1940, 2); System.out.println("ug1 is:"); ug1.writeOutput(); Undergraduate ug2 = new Undergraduate("James Bond", 007, 1); System.out.println("ug2 is:"); ug2.writeOutput(); if (ug1.equals(ug2)) System.out.println("Same students."); else System.out.println("Not the same students."); //sameName inherited from Student, which inherited it fron Person. if (ug1.sameName(ug2)) System.out.println("Same names."); else System.out.println("Not the same names."); } } Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 26 Execution Result of UndergraduateDemo.java Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 27 Character Graphics Example Inherited Overrides Static Figure Box Triangle Instance variables: offset height width Methods: setOffset getOffset drawAt drawHere reset drawHorizontalLine drawSides drawOneLineOfSides spaces Chapter 7 Instance variables: offset Methods: setOffset getOffset drawAt drawHere Instance variables: offset base Methods: setOffset getOffset drawAt drawHere reset drawBase drawTop spaces Java: an Introduction to Computer Science & Programming - Walter Savitch 28 Sample Boxes and Triangles Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 29 /************************************************************** *Class for simple character graphics figures to send to screen. *This class can draw an asterisk on the screen as a test. But, *it is not intended to be a figure used in graphics. *It is intended to be used as a base class for the kinds *of figures that will be used in graphics applications. **************************************************************/ public class Figure { Display 7.7 private int offset; Figure Base Class (1/2) public Figure() { offset = 0; } public Figure(int theOffset) { offset = theOffset; } public void setOffset(int newOffset) { offset = newOffset; } public int getOffset() { return offset; } Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 30 /****************************************** Display 7.7 *Draws the figure at lineNumber lines down Figure Base Class *from the current line. (2/2) ******************************************/ public void drawAt(int lineNumber) { int count; for (count = 0; count < lineNumber; count++) System.out.println(); drawHere(); } /************************************* *Draws the figure at the current line. *************************************/ public void drawHere() { int count; for (count = 0; count < offset; count++) System.out.print(' '); System.out.println('*'); } } Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 31 /****************************************************** *Class for a rectangular box to be drawn on the screen. *Because each character is higher than it is wide, these *boxes will look higher than you might expect. Inherits *getOffset, setOffset, and drawAt from the class Figure. *******************************************************/ public class Box extends Figure Display 7.8 { Box Class private int height; (1/3) private int width; public Box() { super(); height = 0; width = 0; } public Box(int theOffset, int theHeight, int theWidth) { super(theOffset); height = theHeight; width = theWidth; } Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 32 public void reset(int newOffset, int newHeight, int newWidth) { setOffset(newOffset); Display 7.8 height = newHeight; Box Class width = newWidth; (2/3) } /************************************* *Draws the figure at the current line. *************************************/ public void drawHere() { drawHorizontalLine(); drawSides(); drawHorizontalLine(); } private void drawHorizontalLine() { spaces(getOffset()); int count; for (count = 0; count < width; count++) System.out.print('-'); System.out.println(); } Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 33 private void drawSides() { int count; for (count = 0; count < (height - 2); count++) drawOneLineOfSides(); } Display 7.8 private void drawOneLineOfSides() Box Class { (3/3) spaces(getOffset()); System.out.print('|'); spaces(width - 2); System.out.println('|'); } //Writes the indicated number of spaces. private static void spaces(int number) { int count; for (count = 0; count < number; count++) System.out.print(' '); } } Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 34 /***************************************************************** *Class for triangles to be drawn on screen. For this class, *a triangle points up and is completely determined by the size of *its base. (Screen character spacing determines the length of the *sides, given the base.) *Inherits getOffset, setOffset, and drawAt from Figure. *****************************************************************/ public class Triangle extends Figure { Display 7.9 private int base; Triangle Class public Triangle() { super(); base = 0; } public Triangle(int theOffset, int theBase) { super(theOffset); base = theBase; } public void reset(int newOffset, int newBase) { setOffset(newOffset); base = newBase; } Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch (1/3) 35 /******************************* Display 7.9 *Draws the figure at current line. Triangle Class *******************************/ (2/3) public void drawHere() { drawTop(); drawBase(); } private void drawBase() { spaces(getOffset()); int count; for (count = 0; count < base; count++) System.out.print('*'); System.out.println(); } Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 36 private void drawTop() Display 7.9 Triangle Class (3/3) { //startOfLine will be the number of spaces to the first '*' on a //line. Initially set to the number of spaces before the top '*'. int startOfLine = getOffset() + (base/2); spaces(startOfLine); System.out.println('*');//top '*' int count; int lineCount = (base/2) - 1;//height above base //insideWidth == number of spaces between the two '*'s on a line. int insideWidth = 1; for (count = 0; count < lineCount; count++) { //Down one line so the first '*' is one more space to the left. startOfLine--; spaces(startOfLine); System.out.print('*'); spaces(insideWidth); System.out.println('*'); //Down one line so the inside is 2 spaces wider. insideWidth = insideWidth + 2; } } private static void spaces(int number) { int count; for (count = 0; count < number; count++) System.out.print(' '); } } Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 37 public class GraphicsDemo { public static final int public static final int public static final int public static final int Display 7.10 Character Graphics Application indent = 5; topWidth = 21; bottomWidth = 4; bottomHeight = 4; public static void main(String[] args) { System.out.println(" Save the Redwoods!"); Triangle top = new Triangle(indent, topWidth); Box base = new Box(indent + (topWidth/2) – (bottomWidth/2), bottomHeight, bottomWidth); top.drawAt(1); base.drawAt(0); } } Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 38 Execution Result of GraphicsDemo.java Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 39 Example of Abstract Class : Figure Class Redone as An Abstract Class (1/2) /**************************************************************** *Abstract class for simple character graphics figures to send to *screen. It is intended to be used as a base class for the kinds *of figures that will be used in graphics applications. ****************************************************************/ public abstract class Figure { private int offset; public abstract void drawHere(); public Figure() { offset = 0; } public Figure(int theOffset) { offset = theOffset; } Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 40 Figure Class Redone as An Abstract Class (2/2) public void setOffset(int newOffset) { offset = newOffset; } public int getOffset() { return offset; } /****************************************** *Draws the figure at lineNumber lines down *from the current line. ******************************************/ public void drawAt(int lineNumber) { int count; for (count = 0; count < lineNumber; count++) System.out.println(); drawHere(); } } Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 41 How do Programs Know Where to Go Next? Chapter 7 Programs normally execute in sequence Non-sequential execution occurs with: » selection (if/if-else/switch) and repetition (while/do-while/for) (depending on the test it may not go in sequence) » method calls, which jump to the location in memory that contains the method's instructions and returns to the calling program when the method is finished executing One job of the compiler is to try to figure out the memory addresses for these jumps The compiler cannot always know the address » sometimes it needs to be determined at run time Java: an Introduction to Computer Science & Programming - Walter Savitch 42 Static and Dynamic Binding Chapter 7 Binding: determining the memory addresses for jumps Static: done at compile time » also called offline Dynamic: done at run time Compilation is done offline » it is a separate operation done before running a program Binding done at compile time is, therefor, static, and Binding done at run time is dynamic » also called late binding Java: an Introduction to Computer Science & Programming - Walter Savitch 43 Example of Dynamic Binding: General Description Chapter 7 Derived classes call a method in their parent class which calls a method that is overridden (defined) in each of the derived classes » the parent class is compiled separately and before the derived classes are even written » the compiler cannot possibly know which address to use » therefore the address must be determined (bound) at run time Java: an Introduction to Computer Science & Programming - Walter Savitch 44 Dynamic Binding: Specific Example Parent class: Figure » Defines methods: drawAt and drawHere » drawAt calls drawHere Derived class: Box extends Figure » Inherits drawAt » redefines (overrides) drawHere » Calls drawAt – uses the parent's drawAt method – which must call this, the derived class's, drawHere method Figure is compiled before Box is even written, so the address of drawHere(in the derived class Box) cannot be known then » it must be determined during run time, i.e. dynamically Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 45 Polymorphism Chapter 7 Using the process of dynamic binding to allow different objects to use different method actions for the same method name Originally overloading was considered to be polymorphism Now the term usually refers to use of dynamic binding Java: an Introduction to Computer Science & Programming - Walter Savitch 46 Summary Chapter 7 A derived inherits the instance variables & methods of the base class A derived class can create additional instance variables and methods The first thing a constructor in a derived class normally does is call a constructor in the base class If a derived class redefines a method defined in the base class, the version in the derived class overrides that in the base class Private instance variables and methods of a base class cannot be accessed directly in the derived class If A is a derived class of class B, than A is both a member of both classes, A and B » the type of A is both A and B Java: an Introduction to Computer Science & Programming - Walter Savitch 47