Intro to Computer Science 2. Inheritance

Similar documents
Inheritance Advanced Programming ICOM 4015 Lecture 11 Reading: Java Concepts Chapter 13

Inheritance (P1 2006/2007)

Chapter Goals. Chapter 9 Inheritance. Inheritance Hierarchies. Inheritance Hierarchies. Set of classes can form an inheritance hierarchy

Chapter 10 Inheritance. Big Java by Cay Horstmann Copyright 2009 by John Wiley & Sons. All rights reserved.

CHAPTER 10 INHERITANCE

3/7/2012. Chapter Ten: Inheritance. Chapter Goals

Handout 9 OO Inheritance.

Introduction to Inheritance

Check out Polymorphism from SVN. Object & Polymorphism

COSC This week. Will Learn

Inheritance: Definition

CS1083 Week 3: Polymorphism

INHERITANCE. Spring 2019

Inheritance & Abstract Classes Fall 2018 Margaret Reid-Miller

CSSE 220 Day 15. Inheritance. Check out DiscountSubclasses from SVN

CSC Inheritance. Fall 2009

CS-202 Introduction to Object Oriented Programming

INHERITANCE & POLYMORPHISM. INTRODUCTION IB DP Computer science Standard Level ICS3U. INTRODUCTION IB DP Computer science Standard Level ICS3U

UNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 11 CLASSES CONTINUED

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

Principles of Software Construction: Objects, Design and Concurrency. Polymorphism, part 2. toad Fall 2012

Inheritance. Inheritance

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Agenda: Notes on Chapter 3. Create a class with constructors and methods.

Principles of Software Construction: Objects, Design, and Concurrency

Principles of Software Construction: Objects, Design and Concurrency. Inheritance, type-checking, and method dispatch. toad

Implementing Classes

Principles of Software Construction: Objects, Design and Concurrency. Packages and Polymorphism. toad Fall 2012

CMSC131. Inheritance. Object. When we talked about Object, I mentioned that all Java classes are "built" on top of that.

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.

COP 3330 Final Exam Review

STUDENT LESSON A5 Designing and Using Classes

Overview. Lecture 7: Inheritance and GUIs. Inheritance. Example 9/30/2008

Binghamton University. CS-140 Fall Chapter 9. Inheritance

Java Object Oriented Design. CSC207 Fall 2014

Lesson 35..Inheritance

What is Inheritance?

CN208 Introduction to Computer Programming

Super-Classes and sub-classes

Inheritance and Polymorphism

Inheritance and Subclasses

C# Programming for Developers Course Labs Contents

Software and Programming I. Classes and Arrays. Roman Kontchakov / Carsten Fuhs. Birkbeck, University of London

Chapter 5 Object-Oriented Programming

Name Return type Argument list. Then the new method is said to override the old one. So, what is the objective of subclass?

CS 215 Software Design Sample midterm solutions

Implementing Classes (P1 2006/2007)

Practice for Chapter 11

Building Java Programs. Inheritance and Polymorphism

Methods Common to all Classes

The class Object. Lecture CS1122 Summer 2008

Inheritance -- Introduction

Computer Science II (20073) Week 1: Review and Inheritance

Programming a Bank Database. We ll store the information in two tables: INTEGER DECIMAL(10, 2)

Objects and Classes. Lecture 10 of TDA 540 (Objektorienterad Programmering) Chalmers University of Technology Gothenburg University Fall 2017

public class Account { private int id; private static int nextaccountid = 0; private String name; private double balance;

CMSC 132: Object-Oriented Programming II

CH. 2 OBJECT-ORIENTED PROGRAMMING

CLASS DESIGN. Objectives MODULE 4

COMP-202 Unit 8: Defining Your Own Classes. CONTENTS: Class Definitions Attributes Methods and Constructors Access Modifiers and Encapsulation

Inheritance in Ruby. You are familiar with the idea of inheritance and how to use this in programming.

Big software. code reuse: The practice of writing program code once and using it in many contexts.

Principles of Software Construction: Objects, Design, and Concurrency. Part 1: Designing Classes. Design for Reuse School of Computer Science

CS 215 Software Design Sample Midterm Questions

25. Generic Programming

1- Differentiate between extends and implements keywords in java? 2- What is wrong with this code:

Java: introduction to object-oriented features

C++ Important Questions with Answers

Inheritance. Notes Chapter 6 and AJ Chapters 7 and 8

Object Oriented Programming. Java-Lecture 11 Polymorphism

CSCI-1200 Computer Science II Fall 2006 Lecture 23 C++ Inheritance and Polymorphism

COMPUTER SCIENCE DEPARTMENT PICNIC. Operations. Push the power button and hold. Once the light begins blinking, enter the room code

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

CS 106X, Lecture 14 Classes and Pointers

CS/ENGRD 2110 FALL Lecture 6: Consequence of type, casting; function equals

Location: Planet Laser Interview Skills Workshop

More About Objects. Zheng-Liang Lu Java Programming 255 / 282

Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II

Inheritance. Transitivity

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

Inheritance. A mechanism for specialization A mechanism for reuse. Fundamental to supporting polymorphism

The software crisis. code reuse: The practice of writing program code once and using it in many contexts.

1 Shyam sir JAVA Notes

Lecture 4: Extending Classes. Concept

Inheritance (Part 5) Odds and ends

Rules and syntax for inheritance. The boring stuff

Lecture Contents CS313D: ADVANCED PROGRAMMING LANGUAGE. What is Inheritance?

Inheritance (continued) Inheritance

Inheritance (Part 2) Notes Chapter 6

CSC 222: Object-Oriented Programming. Fall Inheritance & polymorphism

CS 61B Data Structures and Programming Methodology. July 3, 2008 David Sun

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

Basic Object-Oriented Concepts. 5-Oct-17

OBJECT ORİENTATİON ENCAPSULATİON

Review. these are the instance variables. these are parameters to the methods

CSC9T4: Object Modelling, principles of OO design and implementation

EXAM Computer Science 1 Part 1

Introduction to Objects. James Brucker

HAS-A Relationship. If A uses B, then it is an aggregation, stating that B exists independently from A.

CS313D: ADVANCED PROGRAMMING LANGUAGE

Transcription:

Intro to Computer Science 2 Inheritance

Admin Questions? Quizzes Midterm Exam Announcement

Inheritance Inheritance Specializing a class

Inheritance Just as In science we have inheritance and specialization Have in 0-0 programming as well. All attributes (instance vars) And abilities (methods) Of general class are available in specialized class.

// OK to use BankAccount method with SavingsAccount Inheritance in Java Inheritance: extend classes by adding methods and fields Example: Savings account = bank account with interest class SavingsAccount extends BankAccount{ new methods new instance fields } SavingsAccount automatically inherits all methods and instance fields of BankAccount SavingsAccount collegefund = new SavingsAccount(10); // Savings account with 10% interest collegefund.deposit(500);

Inheritance Jargon terms Extended class = superclass (BankAccount), extending class = subclass (SavingsAccount) Inheriting from class implementing interface: subclass inherits behavior and state Methods are implemented in superclass One advantage of inheritance is code reuse

UML for inheritance Inheritance relationshp Is-a generalization

Inheritance:subclass In subclass, specify added instance fields, added methods, and changed or overridden methods public class SavingsAccount extends BankAccount{ public SavingsAccount(double rate) { interestrate = rate; } public void addinterest() { double interest = getbalance() * interestrate / 100; deposit(interest); } private double interestrate; } Note that addinterest calls getbalance without specifying an implicit parameter (the calls apply to the same object) Encapsulation: addinterest calls getbalance rather than updating the balance field of the superclass (field is private)

Subclass II SavingsAccount object inherits the balance instance field from BankAccount, and gains one additional instance field: interestrate:

Inheritance Syntax Syntax: class SubclassName extends SuperclassName { methods instance fields } Purpose: To define a new class that inherits from an existing class, and define the methods and instance fields that are added in the new class.

Questions Questions everywhere Which instance fields does an object of class SavingsAccount have? Name four methods that you can apply to SavingsAccount objects If the class Manager extends the class Employee, which class is the superclass and which is the subclass?

Example Inheritance Hierarchy:swing

Sample Hierarchy II Consider a bank that offers its customers the following account types: Checking account: no interest; small number of free transactions per month, additional transactions are charged a small fee Savings account: Inheritance hierarchy: earns interest that compounds monthly

Inheritance and methods 2 of 3 Possibilities Inherit method: Don't supply a new implementation of a method that exists in superclass Superclass method can be applied to the subclass objects Add method: Supply a new method that doesn't exist in the superclass New method can be applied only to subclass objects

Inheritance and Methods II Last and most interesting. Override method: Supply a different implementation of a method that exists in the superclass Must have same signature (same name and same parameter types) If method is applied to an object of the subclass type, the overriding method is executed

Inheriting instance fields Can't override fields Inherit field: All fields from the superclass are automatically inherited Add field: Supply a new field that doesn't exist in the superclass What if you define a new field with the same name as a superclass field? Each object would have two instance fields of the same name Fields can hold different values Legal but extremely undesirable

Access Control Java has four levels of controlling access to fields, methods, and classes: public access Can be accessed by methods of all classes private access Can be accessed only by the methods of their own class protected access This class and all subclasses package access The default, when no access modifier is given Can be accessed by all classes in the same package Good default for classes, but extremely unfortunate for

Var : Recommended Access Instance and static fields: private, possibly protected if you are sure subclasses won't abuse it public static final constants are useful and safe Some objects, such as System.out, need to be accessible to all programs (public) Occasionally, classes in a package must collaborate very closely (give some fields package access); inner classes are usually better

Recommended Access II Methods: public private or protected as needed Classes and interfaces: public or package no reason to have private class unless inner class Better alternative to package access: inner classes

Overriding method example adding a checking account class Overrides deposit and withdraw to increment the transaction count: public class CheckingAccount extends BankAccount { public void deposit(double amount) {... } public void withdraw(double amount) {... } public void deductfees() {... } // new method private int transactioncount; // new instance field }

Examining CheckingAccount class Each CheckingAccount object has two instance fields: balance (inherited from BankAccount) transactioncount (new to CheckingAccount) You can apply four methods to CheckingAccount objects: getbalance() (inherited from BankAccount) deposit(double amount) (overrides BankAccount method) withdraw(double amount) (overrides BankAccount method) deductfees() (new to CheckingAccount)

Invoking superclass method when method is overridden can't just invoke method any more checking account deposit method for example if checking account version of method wants to call super class version how? public void deposit(double amount) { transactioncount++; // now add amount to balance... }

in other words Can't just call deposit(amount) in deposit method of CheckingAccount That is the same as this.deposit(amount) the whole point of method overriding Calls the same method (infinite recursion)

Solution Instead, invoke superclass method super.deposit(amount) Now calls deposit method of BankAccount class Complete method: public void deposit(double amount) { transactioncount++; // Now add amount to balance super.deposit(amount); }

Formal Syntax Syntax: Purpose: super.methodname(parameters) To call a method of the superclass instead of the method of the current class

Error: Shadowing Instance Fields subclass has no access to the private instance fields of the superclass Beginner's error: "solve" this problem by adding another instance field with same name: public class CheckingAccount extends BankAccount{ public void deposit(double amount){ transactioncount++; balance = balance + amount; }... private double balance; // Don't }

Shadowing II Now the deposit method compiles, but it doesn't update the correct balance!

constructor in subclass might need to call superclass constructor super followed by a parenthesis indicates a call to the superclass constructor public class CheckingAccount extends BankAccount{ public CheckingAccount(double initialbalance){ // Construct superclass super(initialbalance); // Initialize transaction count transactioncount = 0; }... }

Subclass constructors II Caveats Must be the first statement in subclass constructor!!!!!! If subclass constructor doesn't call superclass constructor, default superclass constructor is used Default constructor: constructor with no parameters If all constructors of the superclass require parameters, then the compiler reports an error

Syntax: Superclass constructors syntax: ClassName(parameters) { super(parameters);... } Purpose: To invoke a constructor of the superclass. Note that this statement must be the first statement of the subclass constructor.

I knew I should have asked him first! Why didn't the SavingsAccount constructor in from last time call its superclass constructor? When you invoke a superclass method with the super keyword, does the call have to be the first statement of the subclass method?

Subclass and superclass types ok to refer to a subclass object with superclass variable is-a relationship SavingsAccount collegefund = new SavingsAccount(10); BankAccount anaccount = collegefund; Object anobject = collegefund;

Subclass object, superclass var Superclass references don't know the full story: anaccount.deposit(1000); // OK anaccount.addinterest(); // No--not a method of the class to which anaccount belongs

Subclass object, superclass var II When you convert between a subclass object to its superclass type: The value of the reference stays the same it is the memory location of the object But, less information is known about the object Why? Reuse code that knows about the superclass but not the subclass: public void transfer(double amount, BankAccount other){ withdraw(amount); other.deposit(amount); } Can be used to transfer money from any type of BankAccount

converting back to subclass ref Occasionally you need to convert from a superclass reference to a subclass reference BankAccount anaccount = (BankAccount) anobject; This cast is dangerous: if you are wrong, an exception is thrown Solution: use the instanceof operator instanceof: tests whether an object belongs to a particular type if (anobject instanceof BankAccount) { BankAccount anaccount = (BankAccount) anobject;... }

syntax: instanceof Syntax: Example: object instanceof TypeName if (anobject instanceof BankAccount){ BankAccount anaccount = (BankAccount) anobject;... } Purpose: To return true if the object is an instance of TypeName (or one of its subtypes), and false otherwise

Lets see if you remember Why did the second parameter of the transfer method have to be of type BankAccount and not, for example, SavingsAccount? Why can't we change the second parameter of the transfer method to the type Object?

Reading read chapter 9 through section 9.8 (page 615)

More Polymorphism Recall in Java, type of a variable doesn't completely determine type of object to which it refers BankAccount abankaccount = new SavingsAccount(1000); // abankaccount holds a reference to a SavingsAccount interface variables as well Method calls are determined by type of actual object, not type of object reference BankAccount anaccount = new CheckingAccount(); anaccount.deposit(1000); // Calls "deposit" from CheckingAccount

More Polymorphism II Compiler needs to check that only legal methods are invoked Object anobject = new BankAccount(); anobject.deposit(1000); // Wrong! Polymorphism at work: public void transfer(double amount, BankAccount other){ withdraw(amount); // Shortcut for this.withdraw(amount) other.deposit(amount); } Depending on types of amount and other, different versions of withdraw and deposit are called

He's asking more questions again If a is a variable of type BankAccount that holds a non-null reference, what do you know about the object to which a refers? If a refers to a checking account, what is the effect of calling a.transfer(1000, a)? checking account class from earlier slides

Object: Superclass of everything recall All classes defined without an explicit extends clause automatically extend Object

Object Methods Provides about 10 methods most not of interest to us yet but three are String tostring() boolean equals(object otherobject) Object clone() Good idea to override these methods in your classes

// Sets s to something like "BankAccount@d24606bf" tostring Seen earlier: Returns string representation object Useful for debugging: Rectangle box = new Rectangle(5, 10, 20, 30); String s = box.tostring(); // Sets s to "java.awt.rectangle[x=5,y=10,width=20,height=30]" tostring is called whenever you concatenate a string with an object: "box=" + box; Object.toString prints class name and the hash code of the object BankAccount momssavings = new BankAccount(5000); String s = momssavings.tostring();

OverRiding tostring To provide a nicer representation of an object, override tostring: public String tostring() { return "BankAccount[balance=" + balance + "]"; } This works better: BankAccount momssavings = new BankAccount(5000); String s = momssavings.tostring(); // Sets s to "BankAccount[balance=5000]"

Equals method remember equals method string rectangle what do they do?

Equals in Object makes sure that every class has an equals methods in Object class equals implemented as == supposed to test contents equality.

Overriding equals Define the equals method to test whether two objects have equal state When redefining equals method, you cannot change object signature; use a cast instead: public class Coin{... public boolean equals(object otherobject){ Coin other = (Coin) otherobject; return name.equals(other.name) && value == other.value; }...

Questions again Should the call x.equals(x) always return true? Can you implement equals in terms of tostring? Should you?

Protected in UML Protected is represented a more than one way Most commonly using #

Abstract classes Abstract class Class with one or more abstract methods Cannot create instance of abstract class. Used as an incomplete base class for polymorphism

Abstract Method An abstract method is one that has no implementation public class abclass{ public method1(int param); } method1 has no implementation Can create abclass variables But not objects [no new abclass() ] More on board

Abstract Classes in UML Diagram class as usual except Name of abstract class should be in italics signature of abstract methods should be intalics

Abstract Classes in UML Diagram class as usual except Name of abstract class should be in italics signature of abstract methods should be italics

Questions If a subclass extends a superclass with and abstract method, what must you do in the subclass? If a class is defined as abstract, what can you not do with the class?

Reading Read chapter 9 in your book.