Presentation is loading. Please wait.

Presentation is loading. Please wait.

ITM 352 Class inheritance, hierarchies Lecture #.

Similar presentations


Presentation on theme: "ITM 352 Class inheritance, hierarchies Lecture #."— Presentation transcript:

1 ITM 352 Class inheritance, hierarchies Lecture #

2 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!!

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

4 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

5 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

6 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 -

7 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)

8 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

9 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

10 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

11 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

12 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

13 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

14 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

15 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

16 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

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

18 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

19 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):

20 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):

21 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

22 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); }

23 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;

24 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); }

25 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); }

26 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

27 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

28 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

29 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

30 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.

31 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

32 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

33 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

34 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

35 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

36 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

37 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

38 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

39 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

40 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. 1007 Instructor The Robot Warz System The Robot Warz Actors monitors contest uses

41 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

42 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

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

44 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

45 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); }

46 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

47 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

48 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); }

49 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

50 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) {…} }

51 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 ();

52 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();

53 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();

54 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

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

56 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.

57 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); }

58 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)

59 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.

60 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; }

61 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.


Download ppt "ITM 352 Class inheritance, hierarchies Lecture #."

Similar presentations


Ads by Google