Inheritance Itm352 S03

  • Uploaded by: arlenebareno
  • 0
  • 0
  • May 2020
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Inheritance Itm352 S03 as PDF for free.

More details

  • Words: 4,041
  • Pages: 61
ITM 352 Class inheritance, hierarchies Lecture #

Announcements ●

● ●

Chapter 7

Good job on exam 1 » Exam 2 will be a little different Extra lab tomorrow (Friday) 10-12noon Be sure to get started on HW3 » Several parts!!

Java: an Introduction to Computer Science & Programming - Walter Savitch

Topics For Today ● ● ●

Chapter 7

Review of Objects Basic Inheritance UML

Java: an Introduction to Computer Science & Programming - Walter Savitch

Object Abstractions ●

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

s

te ibu

tr At

Chapter 7

Java: an Introduction to Computer Science & Programming - Walter Savitch

Object Relationships ●

Objects interact (share data, invoke operations) through relationships

manages aRobot anEnvironment

owns aWeapon

kool!

Chapter 7

Java: an Introduction to Computer Science & Programming - Walter Savitch

Object Qualities You want to specify the following information for each object: Identity Defining quality Name Attributes Behaviors Relationships State Groups Constraints -

Chapter 7

Java: an Introduction to Computer Science & Programming - Walter Savitch

Classes: Summary ●



Chapter 7

Describe objects of the same type (type-of) » Some qualities – behaviors (methods) – attributes (instance variables) – constraints » Many possible quality resolutions - maintained in objects Describe how an object of a given type is created (instantiated) in any given situation (instance)

Java: an Introduction to Computer Science & Programming - Walter Savitch

Classes and objects (redressed) ●

Every class has objects, or instances, created using the new operation. Think of the class as an object-producing machine.

aRobot

Robot new

anotherRobot

aString

String new

Chapter 7

Java: an Introduction to Computer Science & Programming - Walter Savitch

anotherString

Java Objects ●





Chapter 7

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 Behaviors are instance methods » methods contain operations » do not have to accept or return values Attributes are instance variables » all variables must be typed » defined outside of any method

Java: an Introduction to Computer Science & Programming - Walter Savitch

Objects and Class (redressed) ●





Chapter 7

Directly describing object structures is inefficient » many objects have the same qualities, just different quality resolutions 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” Objects are constructed (instantiated) through their Class definitions

Java: an Introduction to Computer Science & Programming - Walter Savitch

1

But there’s more… Class Inheritance or Where there’s a will, there are relatives

Chapter 7

Java: an Introduction to Computer Science & Programming - Walter Savitch

1

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

1

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

1

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

1

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

1

public class Person { // Instance variable section private String name;

A Person Base Class

// Constructors public Person() { // Default constructor name = "No name yet."; } public Person(String initialName) { // Constructor for just the name name = initialName; } // Set/get methods public void setName(String newName) { name = newName; } public String getName() { return name; } // Other methods public void writeOutput() { System.out.println("Name: " + name); } public boolean sameName(Person otherPerson) { return (this.name.equalsIgnoreCase(otherPerson.name)); }

Display 7.1

} Chapter 6

Java: an Introduction to Computer Science & Programming - Walter Savitch

1

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

1

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

1

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

2

More about Constructors in a Derived Class ● ●







Chapter 7

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

2

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

2

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

2

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

2

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

2

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

2

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

2

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

2

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

2

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; Not allowed boss = josephine;

Chapter 7

Java: an Introduction to Computer Science & Programming - Walter Savitch

Person

Employee Person is the parent class of Employee in this example.

3

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

3

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

3

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

3

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

3

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

3

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

3

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

3

UML ● ● ● ●

Chapter 7

Universal Modeling Language Used to facilitate OOAD A “standard” choice in many development efforts UML is one approach commonly incorporated into object oriented modeling software, such as Rational Rose

Java: an Introduction to Computer Science & Programming - Walter Savitch

3

UML in ITM 352 (and 353) ●

Chapter 7

We will use only very basic UML » Use-case diagrams » Object relationship diagrams » Basic class (object types) diagrams – association, part-of, kind-of

Java: an Introduction to Computer Science & Programming - Walter Savitch

3

Example Use-case add new robot

uses

starts contest

submits robot to contest

monitors contest

gets contest results

The Robot Warz System

Contest Admin. 1007 Student

Chapter 7

The Robot Warz Actors

1007 Instructor

Java: an Introduction to Computer Science & Programming - Walter Savitch

4

Example Use-case

Contest Admin. Interface

set up contest environment

run contest

Contest Display

Behavior

starts contest

Contest Admin.

Chapter 7

Java: an Introduction to Computer Science & Programming - Walter Savitch

4

Example Class diagram destination object

reference source object part-of relationship

:Robot

m yE nvironm ent

:E nvironm ent

rob otP arts

relationship

:R obotP art

:P lay P en

sub-class relationship

:W eapon :E ngine : R adar

Chapter 7

Java: an Introduction to Computer Science & Programming - Walter Savitch

4

More Examples of Inheritance

Chapter 7

Java: an Introduction to Computer Science & Programming - Walter Savitch

4

Bank Accounts ●

Consider these three classes:

BankAccount holds money SavingsAccount earns interest on money held

CheckingAccount writes checks on money held

Chapter 7

Java: an Introduction to Computer Science & Programming - Walter Savitch

4

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 7

Java: an Introduction to Computer Science & Programming - Walter Savitch

4

Sub-types ●





Chapter 7

SavingsAccount and CheckingAccount » Use all the behaviors of a BankAccount » Use all the attributes of a BankAccount » Add some new behaviors and attributes 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 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

Java: an Introduction to Computer Science & Programming - Walter Savitch

4

Inheritance ● ●

Chapter 7

Both implementation approaches are somewhat in-elegant Java supports a more elegant approach, inheritance » Use the extends keyword in the class definition

Java: an Introduction to Computer Science & Programming - Walter Savitch

4

Inheritance (cont.) public class SavingsAccount extends BankAccount private double interestRate; {

public SavingsAccount(double rate) {

interestRate = rate;

} public void addInterest() { 100;

double interest = getBalance() * interestRate / deposit(interest);

} } Chapter 7

Java: an Introduction to Computer Science & Programming - Walter Savitch

4

Terminology ● ●

BankAccount is called the superclass or base class. SavingsAccount and CheckingAccount are subclasses or

derived classes.

BankAccount ●

Chapter 7

We say SavingsAccount and CheckingAccount inherit from BankAccount , because they obtain the definitions of getBalance and deposit, etc. CheckingAccount SavingsAccount

Java: an Introduction to Computer Science & Programming - Walter Savitch

4

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 7

Java: an Introduction to Computer Science & Programming - Walter Savitch

5

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 7

Java: an Introduction to Computer Science & Programming - Walter Savitch

5

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 7

Java: an Introduction to Computer Science & Programming - Walter Savitch

5

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 7

Java: an Introduction to Computer Science & Programming - Walter Savitch

5

Object Class ●

Actually there is implicitly more inheritance

Object

BankAccount



Everything is a Kind-of Object in Java CheckingAccount SavingsAccount » Any class that does not specify an extension extends Object

Chapter 7

Java: an Introduction to Computer Science & Programming - Walter Savitch

5

UML Inheritance Notation

:Robot

super-class

m yE nvironm ent

:E nvironm ent

rob otP arts :R obotP art

:P lay P en

sub-class relationship

:W eapon :E ngine : R adar

Chapter 7

sub-class

Java: an Introduction to Computer Science & Programming - Walter Savitch

5

A Small Problem… ●



Chapter 7

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.

Java: an Introduction to Computer Science & Programming - Walter Savitch

5

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 7

Java: an Introduction to Computer Science & Programming - Walter Savitch

5

Method redefinition in subclasses ●







Chapter 7

A very important aspect of inheritance is that instance methods can be redefined instead of being inherited. Sometimes this is called overriding 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 Why would you do this? » To modify the behavior of the superclass » In general you try to limit overriding (elegance again)

Java: an Introduction to Computer Science & Programming - Walter Savitch

5

Overriding: Checking Account ●



Chapter 7

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.

Java: an Introduction to Computer Science & Programming - Walter Savitch

5

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 7

Java: an Introduction to Computer Science & Programming - Walter Savitch

6

Inheritance in the Java API ●

Chapter 7

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.

Java: an Introduction to Computer Science & Programming - Walter Savitch

6

Related Documents

Inheritance
November 2019 34
Inheritance
June 2020 21
Inheritance
October 2019 32
S03-04_usesfsheet
November 2019 13
S03-04_usesfbooklet
November 2019 18

More Documents from "REBogart"

May 2020 0
L01_intro
May 2020 0