ITM 352 Class inheritance, hierarchies Lecture #.

Slides:



Advertisements
Similar presentations
Chapter 13 - Inheritance. Goals To learn about inheritance To learn about inheritance To understand how to inherit and override superclass methods To.
Advertisements

Module 8 “Polymorphism and Inheritance”. Outline Understanding Inheritance Inheritance Diagrams Constructors in Derived Classes Type Compatibility Polymorphism.
1 l Inheritance Basics l Programming with Inheritance l Dynamic Binding and Polymorphism Inheritance.
CS 106 Introduction to Computer Science I 04 / 11 / 2008 Instructor: Michael Eckmann.
Inheritance Part I. Lecture Objectives To learn about inheritance To understand how to inherit and override superclass methods To be able to invoke superclass.
Inheritance Inheritance Reserved word protected Reserved word super
I NHERITANCE Chapter 10. I NHERITANCE Mechanism for enhancing existing classes You need to implement a new class You have an existing class that represents.
Introduction To Scientific Programming Chapter 7 – Inheritance or (More on Classes)
1 CS 171: Introduction to Computer Science II Review: OO, Inheritance, and Libraries Ymir Vigfusson.
ACM/JETT Workshop - August 4-5, :Inheritance and Interfaces.
Chapter 13 Inheritance. An Introduction to Inheritance Inheritance: extend classes by adding methods and fields (variables) Example: Savings account =
CHAPTER 11 INHERITANCE CHAPTER GOALS To understand how to inherit and override superclass methods To be able to invoke superclass constructors To learn.
Chapter 9 – Inheritance Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Inheritance Part III. Lecture Objectives To learn about inheritance To understand how to inherit and override superclass methods To be able to invoke.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
CS 106 Introduction to Computer Science I 04 / 16 / 2010 Instructor: Michael Eckmann.
Object Oriented Design CSC 171 FALL 2001 LECTURE 12.
Chapter 10  Inheritance 1 Chapter 10 Inheritance.
1 Chapter 7 l Inheritance Basics l Programming with Inheritance l Dynamic Binding and Polymorphism Inheritance.
CS 106 Introduction to Computer Science I 11 / 15 / 2006 Instructor: Michael Eckmann.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
Inheritance Part II. Lecture Objectives To learn about inheritance To understand how to inherit and override superclass methods To be able to invoke superclass.
OOP in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Inheritance and Subclasses in Java CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo de Manila University.
(c) University of Washington04-1 CSC 143 Java Inheritance Example (Review)
Programming Languages and Paradigms Object-Oriented Programming.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
CS 106 Introduction to Computer Science I 04 / 13 / 2007 Friday the 13 th Instructor: Michael Eckmann.
Chapter 8 More Object Concepts
CISC6795: Spring Object-Oriented Programming: Polymorphism.
CSE 501N Fall ‘09 15: Polymorphism October 22, 2009 Nick Leidenfrost.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Inheritance.
Often categorize concepts into hierarchies: Inheritance Hierarchies Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
CSE 501N Fall ‘09 14: Inheritance 20 October 2009 Nick Leidenfrost.
Inheritance in Java. RHS – SOC 2 What is inheritance (in Java)? Inheritance is a mechanism for enhancing existing classes What does that mean…? Defining.
 Sometimes a new class is a special case of the concept represented by another ◦ A SavingsAccount is-a BankAccount ◦ An Employee is-a Person  Can extend.
Inheritance CSC 171 FALL 2004 LECTURE 18. READING Read Horstmann, Chapter 11.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Topic 4 Inheritance.
CHAPTER 11 INHERITANCE. CHAPTER GOALS To understand how to inherit and override superclass methods To be able to invoke superclass constructors To learn.
CSC 205 Java Programming II Inheritance Inheritance In the real world, objects aren’t usually one-of-a-kind. Both cars and trucks are examples of.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
Chapter 10 Inheritance. Chapter Goals To learn about inheritance To understand how to inherit and override superclass methods To be able to invoke superclass.
Object-Oriented Programming Chapter Chapter
Object Oriented Programming
Chapter 10: Introduction to Inheritance. Objectives Learn about the concept of inheritance Extend classes Override superclass methods Call constructors.
Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism.
 Sometimes a new class is a special case of the concept represented by another ◦ A SavingsAccount is-a BankAccount ◦ An Employee is-a Person  Can extend.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Chapter 13 Inheritance. Chapter Goals To learn about inheritance To understand how to inherit and override superclass methods To be able to invoke superclass.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 6 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
 Description of Inheritance  Base Class Object  Subclass, Subtype, and Substitutability  Forms of Inheritance  Modifiers and Inheritance  The Benefits.
COMPUTER SCIENCE & TECHNOLOGY DEGREE PROGRAMME FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UVA WELLASSA ‏ Properties of Object Oriented Programming.
Notices Assn 2 is due tomorrow, 7pm. Moodle quiz next week – written in the lab as before. Everything up to and including today’s lecture: Big Topics are.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Chapter 13 - Inheritance.
Inheritance Chapter 7 Inheritance Basics Programming with Inheritance
Lecture Notes – Inheritance (Ch 9-10)
Inheritance in Java.
Inheritance Chapter 7 Inheritance Basics Programming with Inheritance
Inheritance Basics Programming with Inheritance
Inheritance, Polymorphism, and Interfaces. Oh My
Computer Programming with JAVA
Inheritance Chapter 7 Inheritance Basics Programming with Inheritance
Inheritance Chapter 7 Inheritance Basics Programming with Inheritance
Presentation transcript:

ITM 352 Class inheritance, hierarchies Lecture #

Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 2 Announcements l Good job on exam 1 »Exam 2 will be a little different l Extra lab tomorrow (Friday) 10-12noon l Be sure to get started on HW3 »Several parts!!

Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 3 Topics For Today l Review of Objects l Basic Inheritance l UML

Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 4 l An abstraction that represents both memory and functionality »memory: resolution of a component’s static qualities such as attributes and relationships. »Functionality: set of methods that embody operations Object Abstractions Attributes

Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 5 Object Relationships l Objects interact (share data, invoke operations) through relationships kool! manages owns anEnvironment aWeapon aRobot

Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 6 Object Qualities You want to specify the following information for each object: Identity - Defining quality - Name - Attributes - Behaviors - Relationships - State Groups - Constraints -

Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 7 Classes: Summary l Describe objects of the same type (type-of) »Some qualities –behaviors (methods) –attributes (instance variables) –constraints »Many possible quality resolutions - maintained in objects l Describe how an object of a given type is created (instantiated) in any given situation (instance)

Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 8 Classes and objects (redressed) Every class has objects, or instances, created using the new operation. Think of the class as an object-producing machine. new Robot String aRobot anotherRobot aString anotherString

Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 9 Java Objects l Literally an instance of a Class (which shockingly is itself, an object!) »Class defines and creates (instantiates) an object »always have a reference after instantiation l Behaviors are instance methods »methods contain operations »do not have to accept or return values l Attributes are instance variables »all variables must be typed »defined outside of any method

Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 10 Objects and Class (redressed) l Directly describing object structures is inefficient »many objects have the same qualities, just different quality resolutions l Java uses the concept of a Class to group the same “type-of” objects together »A Class contains the description on how to create objects of particular type. Sometimes called a “factory object” or “metaobject” l Objects are constructed (instantiated) through their Class definitions

Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 11 But there’s more… Class Inheritance or Where there’s a will, there are relatives

Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 12 Chapter 7 l Inheritance Basics l Programming with Inheritance l Dynamic Binding and Polymorphism Inheritance

Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 13 Principles of OOP l OOP - Object-Oriented Programming l Principles discussed in previous chapters: »Information Hiding »Encapsulation »Polymorphism l In this chapter »Inheritance

Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 14 Why OOP? l To try to deal with the complexity of programs l To apply principles of abstraction to simplify the tasks of writing, testing, maintaining and understanding complex programs l 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?") l Inheritance is a major technique for realizing these objectives

Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 15 Inheritance Overview l 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 l 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 l After the general class is developed you only have to write the "difference" or "specialization" code for each derived class l 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 7Java: an Introduction to Computer Science & Programming - Walter Savitch 16 An Example of Inheritance: a Person Class The base class: Display 7.1 l Constructors: »a default constructor »one that initializes the name attribute (instance variable) l 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 l 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

A Person Base Class Display 7.1 Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 17

Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 18 Derived Classes: a Class Hierarchy l The base class can be used to implement specialized classes »For example: student, employee, faculty, and staff l Classes can be derived from the classes derived from the base class, etc., resulting in a class hierarchy Person StudentEmployee FacultyStaffUndergraduateGraduate MastersDegreeNonDegreePhD

Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 19 Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 19 Example of Adding Constructor in a Derived Class: Student l 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 public class Student extends Person { private int studentNumber; public Student() { super(); studentNumber = 0; } … Keyword extends in first line »creates derived class from base class »this is inheritance The first few lines of Student class (Display 7.3):

Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 20 Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 20 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 7Java: an Introduction to Computer Science & Programming - Walter Savitch 21 More about Constructors in a Derived Class l 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 »shown on the next slide l Whichever is used must be the first action taken by the constructor l 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

Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 22 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 7Java: an Introduction to Computer Science & Programming - Walter Savitch 23 Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 23 Example of Adding an Attribute in a Derived Class: Student l Note that an attribute for the student number has been added »Student has this attribute in addition to name, which is inherited from Person A line from the Student class: private int studentNumber;

Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 24 Example of Overriding a Method in a Derived Class: Student Both parent and derived classes have a writeOutput method l Both methods have the same parameters (none) »they have the same signature l The method from the derived class overrides (replaces) the parent's l It will not override the parent if the parameters are different (since they would have different signatures) l This is overriding, not overloading public void writeOutput() { System.out.println("Name: " + getName()); System.out.println("Student Number : " studentNumber); }

Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 25 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 7Java: an Introduction to Computer Science & Programming - Walter Savitch 26 Overriding Verses Overloading Overriding l Same method name l Same signature l One method in ancestor, one in descendant Overloading l Same method name l Different signature l Both methods can be in same class

Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 27 The final Modifier l Specifies that a method definition cannot be overridden with a new definition in a derived class l Example: public final void specialMethod() {... l Used in specification of some methods in standard libraries l Allows the compiler to generate more efficient code l Can also declare an entire class to be final, which means it cannot be used as a base class to derive another class

Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 28 private & public Instance Variables and Methods 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

Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 29 What is the "Type" of a Derived class? l Derived classes have more than one type l Of course they have the type of the derived class (the class they define) l 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

Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 30 Assignment Compatibility l Can assign an object of a derived class to a variable of any ancestor type Person josephine; Employee boss = new Employee(); josephine = boss; l 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 OK Person Employee Person is the parent class of Employee in this example.

Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 31 Character Graphics Example Figure BoxTriangle Instance variables: offset Methods: setOffsetgetOffset drawAtdrawHere Instance variables: offsetheightwidth Methods: setOffsetgetOffset drawAtdrawHere resetdrawHorizontalLine drawSidesdrawOneLineOfSides spaces Instance variables: offsetbase Methods: setOffsetgetOffset drawAtdrawHere resetdrawBase drawTopspaces Inherited Overrides Static

Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 32 How do Programs Know Where to Go Next? l Programs normally execute in sequence l 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 l One job of the compiler is to try to figure out the memory addresses for these jumps l The compiler cannot always know the address »sometimes it needs to be determined at run time

Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 33 Static and Dynamic Binding l Binding: determining the memory addresses for jumps l Static: done at compile time »also called offline l Dynamic: done at run time l Compilation is done offline »it is a separate operation done before running a program l Binding done at compile time is, therefor, static, and l Binding done at run time is dynamic »also called late binding

Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 34 Example of Dynamic Binding: General Description l 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

Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 35 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 7Java: an Introduction to Computer Science & Programming - Walter Savitch 36 Polymorphism l Using the process of dynamic binding to allow different objects to use different method actions for the same method name l Originally overloading was considered to be polymorphism l Now the term usually refers to use of dynamic binding

Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 37 Summary l A derived inherits the instance variables & methods of the base class l A derived class can create additional instance variables and methods l The first thing a constructor in a derived class normally does is call a constructor in the base class l If a derived class redefines a method defined in the base class, the version in the derived class overrides that in the base class l Private instance variables and methods of a base class cannot be accessed directly in the derived class l 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

Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 38 UML l Universal Modeling Language l Used to facilitate OOAD l A “standard” choice in many development efforts l UML is one approach commonly incorporated into object oriented modeling software, such as Rational Rose

Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 39 UML in ITM 352 (and 353) l We will use only very basic UML »Use-case diagrams »Object relationship diagrams »Basic class (object types) diagrams –association, part-of, kind-of

Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 40 Example Use-case add new robotstarts contest submits robot to contest gets contest results 1007 Student Contest Admin Instructor The Robot Warz System The Robot Warz Actors monitors contest uses

Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 41 Example Use-case starts contest Contest Admin. Interface set up contest environment run contest Contest Display Behavior

Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 42 Example Class diagram reference source object relationship destination object part-of relationship sub-class relationship

Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 43 More Examples of Inheritance

Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 44 Bank Accounts l Consider these three classes: BankAccount SavingsAccount CheckingAccount holds money earns interest on money held writes checks on money held

Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 45 public class BankAccount { private double balance; public BankAccount() { balance = 0; } public BankAccount(double initialBalance) { balance = initialBalance; } public void deposit(double amount) { balance = balance + amount; } public void withdraw(double amount) { balance = balance - amount; } public double getBalance() { return balance; } public void transfer(BankAccount other, double amount) { withdraw(amount); other.deposit(amount); }

Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 46 Sub-types l SavingsAccount and CheckingAccount »Use all the behaviors of a BankAccount »Use all the attributes of a BankAccount »Add some new behaviors and attributes l This is because they are both types-of BankAccount »They are a “kind-of” BankAccount »A specialization or sub-type »We are intentionally making a distinction l To implement we could »Create two new classes and simply copy all the instance methods and instance variables from BankAccount and add the new stuff »Add new behaviors and attributes to BankAccount and use conditionals to determine when savings vs. checking

Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 47 Inheritance l Both implementation approaches are somewhat in-elegant l Java supports a more elegant approach, inheritance »Use the extends keyword in the class definition

Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 48 Inheritance (cont.) public class SavingsAccount extends BankAccount private double interestRate; { public SavingsAccount(double rate) { interestRate = rate; } public void addInterest() { double interest = getBalance() * interestRate / 100; deposit(interest); }

Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 49 Terminology BankAccount is called the superclass or base class. SavingsAccount and CheckingAccount are subclasses or derived classes. We say SavingsAccount and CheckingAccount inherit from BankAccount, because they obtain the definitions of getBalance and deposit, etc. SavingsAccount BankAccount CheckingAccount

Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 50 What this means SavingsAccount has five operations: deposit, withdraw, getBalance, transfer, addInterest It is as if SavingsAccount were defined as public class SavingsAccount { private double balance; private double interestRate; public SavingsAccount(){ … } public SavingsAccount(double initialBalance) { … } public void deposit(double amount) { … } public void withdraw(double amount) { … } public double getBalance() { … } public void transfer(BankAccount other, double amount) {…} }

Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 51 What this means (cont.) Similarly for CheckingAccount. Variables can be declared of type BankAccount. SavingsAccount and CheckingAccount objects can be assigned to them. BankAccount mySavingsAccount = new SavingsAccount(), myCheckingAccount = new CheckingAccount ();

Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 52 Casting and Converting Both can use any methods and ivars from BankAccount mySavingsAccount.deposit(100); myCheckingAccount.withdrawal(1000); myCheckingAccount.transfer(mySavingsAccount, 100); But not mySavingsAccount.addInterest(); You can re-cast if needed SavingsAccount aSavingsAccount = (SavingsAccount) mySavingsAccount aSavingsAccount.addInterest();

Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 53 new conditional operator Because you may declare a reference to one of its super classes (including Object ), you may need to test if a reference is the type you desire. Java uses the instanceof operator for this purpose if(myAccount instanceof SavingsAccount) myAccount.addInterest();

Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 54 Object Class l Actually there is implicitly more inheritance Everything is a Kind-of Object in Java »Any class that does not specify an extension extends Object SavingsAccount BankAccount CheckingAccount Object

Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 55 UML Inheritance Notation sub-class super-class sub-class relationship

Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 56 A Small Problem… l Sometimes you will need to initialize a subclasses instance variables (in a constructor) but not know (or care) how the superclass initializes the inherited ones. Java provides a simple solution to this using the super operation.

Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 57 super public class SavingsAccount extends BankAccount private double interestRate; { public SavingsAccount(double rate, double startingBal) { super(startingBal); interestRate = rate; } public void addInterest() { double interest = getBalance() * interestRate / 100; deposit(interest); }

Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 58 Method redefinition in subclasses l A very important aspect of inheritance is that instance methods can be redefined instead of being inherited. Sometimes this is called overriding l You do this by simply using the exact same method name (including parameters and return type) Real rule is: if B is a subclass of A then it inherits instance variables of A and instance methods of A, except those that it defines itself. »Instance variables are not overridden – if B re-defines ivars then there would be two independent (local to each class) versions l Why would you do this? »To modify the behavior of the superclass »In general you try to limit overriding (elegance again)

Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 59 Overriding: Checking Account A CheckingAccount may want to modify the behavior of the deposit, withdrawal, and transfer methods of BankAccount in order to keep track of the number of transactions (to asses a use fee). The super keyword can be used to call a method of the superclass if the modifications are additions only.

Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 60 public class CheckingAccount extends BankAccount { public CheckingAccount(double initialBalance) { // construct superclass super(initialBalance); // initialize transaction count transactionCount = 0; } public void deposit(double amount) { transactionCount++; // now add amount to balance super.deposit(amount); } public void withdraw(double amount) { transactionCount++; // now subtract amount from balance super.withdraw(amount); } public void deductFees() { if (transactionCount > FREE_TRANSACTIONS) { double fees = TRANSACTION_FEE * (transactionCount - FREE_TRANSACTIONS); super.withdraw(fees); } transactionCount = 0; } private int transactionCount; private static final int FREE_TRANSACTIONS = 3; private static final double TRANSACTION_FEE = 2.0; }

Chapter 7Java: an Introduction to Computer Science & Programming - Walter Savitch 61 Inheritance in the Java API l Inheritance is used extensively in the Java API »The Applet class has definitions of init, paint, repaint, etc. When you define an applet, you inherit those definitions and redefine the ones you choose to. »Applet itself inherits from its superclass, Panel, which in turn inherits from Container, which inherits from Component.