Chapter 13 - Inheritance



Similar documents
D06 PROGRAMMING with JAVA

ICOM 4015: Advanced Programming

CS193j, Stanford Handout #10 OOP 3

Java Interview Questions and Answers

D06 PROGRAMMING with JAVA. Ch3 Implementing Classes

Abstract Classes. Suppose we want write a program that manipulates various types of bank accounts. An Account typically has following features;

Java Programming Language

CS 111 Classes I 1. Software Organization View to this point:

Inheritance, overloading and overriding

AP Computer Science Java Subset

CSCI 253. Object Oriented Programming (OOP) Overview. George Blankenship 1. Object Oriented Design: Java Review OOP George Blankenship.

5. Advanced Object-Oriented Programming Language-Oriented Programming

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

3 Pillars of Object-oriented Programming. Industrial Programming Systems Programming & Scripting. Extending the Example.

Java: overview by example

JAVA - INHERITANCE. extends is the keyword used to inherit the properties of a class. Below given is the syntax of extends keyword.

History OOP languages Year Language 1967 Simula Smalltalk

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Programming by Contract. Programming by Contract: Motivation. Programming by Contract: Preconditions and Postconditions

Java (12 Weeks) Introduction to Java Programming Language

Contents. 9-1 Copyright (c) N. Afshartous

Java CPD (I) Frans Coenen Department of Computer Science

Yosemite National Park, California. CSE 114 Computer Science I Inheritance

UML Class Diagrams. Lesson Objectives

11 November

The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1

java Features Version April 19, 2013 by Thorsten Kracht

D06 PROGRAMMING with JAVA

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Programmation 2. Introduction à la programmation Java

Java Interfaces. Recall: A List Interface. Another Java Interface Example. Interface Notes. Why an interface construct? Interfaces & Java Types

Introduction to Object-Oriented Programming

Lecture 7 Notes: Object-Oriented Programming (OOP) and Inheritance

Building Java Programs

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Description of Class Mutation Mutation Operators for Java

C++ INTERVIEW QUESTIONS

Summit Public Schools Summit, New Jersey Grade Level / Content Area: Mathematics Length of Course: 1 Academic Year Curriculum: AP Computer Science A

Computing Concepts with Java Essentials

Preet raj Core Java and Databases CS4PR. Time Allotted: 3 Hours. Final Exam: Total Possible Points 75

Java Basics: Data Types, Variables, and Loops

core. Volume I - Fundamentals Seventh Edition Sun Microsystems Press A Prentice Hall Title ULB Darmstadt

The Interface Concept

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

SE 360 Advances in Software Development Object Oriented Development in Java. Polymorphism. Dr. Senem Kumova Metin

Agenda. What is and Why Polymorphism? Examples of Polymorphism in Java programs 3 forms of Polymorphism

Object Oriented Software Design

J a v a Quiz (Unit 3, Test 0 Practice)

JAVA - EXCEPTIONS. An exception can occur for many different reasons, below given are some scenarios where exception occurs.

Glossary of Object Oriented Terms

The Sun Certified Associate for the Java Platform, Standard Edition, Exam Version 1.0

Python for Rookies. Example Examination Paper

Fundamentals of Java Programming

Outline of this lecture G52CON: Concepts of Concurrency

CS170 Lab 11 Abstract Data Types & Objects

An Introduction to Classes

CIS 190: C/C++ Programming. Polymorphism

In order to understand Perl objects, you first need to understand references in Perl. See perlref for details.

Exception Handling. Overloaded methods Interfaces Inheritance hierarchies Constructors. OOP: Exception Handling 1

Android Application Development Course Program

Part 3: GridWorld Classes and Interfaces

Introduction: Abstract Data Types and Java Review

An Introduction To UML Class Diagrams Classes

PHP Object Oriented Classes and objects

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Java Application Developer Certificate Program Competencies

Java 6 'th. Concepts INTERNATIONAL STUDENT VERSION. edition

Part I. Multiple Choice Questions (2 points each):

D06 PROGRAMMING with JAVA

CS1002: COMPUTER SCIENCE OO MODELLING & DESIGN: WEEK 5

Moving from CS 61A Scheme to CS 61B Java

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C

Case studies: Outline. Requirement Engineering. Case Study: Automated Banking System. UML and Case Studies ITNP090 - Object Oriented Software Design

Introduction to Java Lecture Notes. Ryan Dougherty

Object-Oriented Programming: Polymorphism

Lecture 15: Inheritance

Object Oriented Software Design

TypeScript for C# developers. Making JavaScript manageable

It has a parameter list Account(String n, double b) in the creation of an instance of this class.

AP Computer Science A - Syllabus Overview of AP Computer Science A Computer Facilities

Using Inheritance and Polymorphism

Abstract Class & Java Interface

3 Improving the Crab more sophisticated programming

Object-Oriented Programming in C# (VS 2010)

Programming Language Concepts: Lecture Notes

Facebook Twitter YouTube Google Plus Website

Advanced Data Structures

I. INTRODUCTION. International Journal of Computer Science Trends and Technology (IJCST) Volume 3 Issue 2, Mar-Apr 2015

An Approach to Programming Based on Concepts

Cohort: BCA/07B/PT - BCA/06/PT - BCNS/06/FT - BCNS/05/FT - BIS/06/FT - BIS/05/FT - BSE/05/FT - BSE/04/PT-BSE/06/FT

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

CMPT 183 Foundations of Computer Science I

Designing with Exceptions. CSE219, Computer Science III Stony Brook University

Object-Oriented Programming Lecture 2: Classes and Objects

Comp 411 Principles of Programming Languages Lecture 34 Semantics of OO Languages. Corky Cartwright Swarat Chaudhuri November 30, 20111

Object Oriented Programming and the Objective-C Programming Language 1.0. (Retired Document)

Chapter 2 Introduction to Java programming

Debugging. Common Semantic Errors ESE112. Java Library. It is highly unlikely that you will write code that will work on the first go

Transcription:

Goals Chapter 13 - Inheritance To learn about inheritance To understand how to inherit and override superclass methods To be able to invoke superclass constructors To learn about protected and package access control To understand the common superclass Object and to override its tostring and equals methods In OOP languages, new classes can be derived from an existing class. Why? organizes related classes reduces code redundancy increases code reuse enables polymorphic references 13.1 Introduction to Inheritance Inheritance: extend classes by adding methods and fields Example: Savings account is a bank account with interest class SavingsAccount extends BankAccount new methods new instance fields SavingsAccount automatically inherits all methods and instance fields of BankAccount SavingsAccount SavingsAccount collegefund = new SavingsAccount(10); // Savings account with 10% interest collegefund.deposit(500); // OK to use BankAccount method with SavingsAccount // object Original/base class is known as the superclass (BankAccount) extending class is the subclass (SavingsAccount) 1

Inheritance vs Interface Every class extends the Object class either directly or indirectly Inheriting from class IS NOT the same as implementing interface subclass inherits behavior and state Interfaces have no state or defined behavior (only names of shared methods) Code Reuse One advantage of inheritance is code reuse Not reinventing the wheel Already have a class that does some base functions, why not just build up on it? Deposit, withdraw, getbalance common among all accounts In subclass, specify added instance fields, added methods, and changed or overridden methods Inheritance takes care of what is common, you define what is different public class SavingsAccount extends BankAccount private double interestrate; public SavingsAccount(double rate) interestrate = rate; public void addinterest() double interest = getbalance() * interestrate / 100; deposit(interest); Encapsulation Why do we call getbalance? double interest = getbalance() * interestrate / 100; SavingsAccount object inherits the balance instance field from BankAccount,, and gains one additional instance field: interestrate SavingsAccount Encapsulation: addinterest calls getbalance because balance field of the superclass is private Cannot access private members of another class (even a subclass!) 2

Syntax Note that addinterest calls getbalance without specifying an implicit parameter (the calls apply to the same object) class SubclassName extends SuperclassName methods instance fields Means the call to is getbalance is applied to the same object as the object that called addinterest 13.2 Inheritance Hierarchies Inheritance is a way to categorize In real world, categories often use hierarchies Generic items yield more specific items Bird Robin, Blue Jay, Cardinal, etc. Sets of classes can form complex inheritance hierarchies Hierarchy What is the common set of features? Superclass There are all birds class Bird ISA Hierarchy What is at the top of every hierarchy? Example 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: earns interest that compounds monthly 3

Inheritance Hierarchy Behaviors All bank accounts support the getbalance method All bank accounts support the deposit and withdraw methods, but the implementations differ Checking account needs a method deductfees; savings account needs a method addinterest 13.3 Inheriting Instance Fields and Methods A subclass can define additional instance fields and methods With existing methods They can override definitions from the superclass They can inherit them as is Overriding methods 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 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 4

Inheriting Instance Fields Can't override fields Inherit field: All fields from the superclass are automatically inherited (but may not be visible) Add field: Supply a new field that doesn't exist in the superclass Inheriting Methods 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 Another instance of shadowing CheckingAccount Class Overrides deposit and withdraw to increment the transaction count: public class CheckingAccount extends BankAccount private int transactioncount; ; // new instance field Each CheckingAccount object has two instance fields: balance (inherited( from BankAccount) transactioncount (new to CheckingAccount) public void deposit(double amount)... public void withdraw(double amount)... public void deductfees()... // new method Inheriting Private fields You can apply four methods to CheckingAccount objects: getbalance() (inherited( from BankAccount deposit(double amount) (overrides method) BankAccount method amount) (overrides withdraw(double amount) ( BankAccount method) BankAccount) deductfees() (new to CheckingAccount) Consider deposit method of CheckingAccount public void deposit(double amount) transactioncount++; // now add amount to balance 5

Inheriting Private fields Consider deposit method of CheckingAccount public void deposit(double amount) transactioncount++; // now add amount to balance balance = balance + amount; Can't just add amount to balance balance is a private field of the superclass A subclass has no access to private fields of its superclass Subclass must use public interface Will this work? Inheriting Private fields Consider deposit method of CheckingAccount public void deposit(double amount) transactioncount++; // now add amount to balance deposit(amount); Will this work? Invoking a Superclass Method Can't just call deposit(amount) in deposit method of CheckingAccount That is the same as this.deposit(amount) //Checking account! Calls the same method (infinite recursion) Solution: super Java allows you to specify calling a method of the super class with the keyword super Invoke superclass method super.deposit(amount.deposit(amount) public void deposit(double amount) transactioncount++; // Now add amount to balance super.deposit(amount); Now calls deposit method of BankAccount class 6

public class CheckingAccount extends BankAccount private static final int FREE_TRANSACTIONS = 3; private static final double TRANSACTION_FEE = 2.0;... 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; Object Class a class extends Object by default when no extends clause is used, e.g: class Thing... class Thing extends Object... Override (redefine) We can override public (and protected) methods of any superclass Use the same signature to override an inherited method. 13.4 Inheritance and Constructors Unlike members and methods of a superclass, constructors of a superclass are not inherited by its subclasses. You must define a constructor for a subclass or use the default constructor added by the compiler. How do you initialize superclass fields though In SavingsAccount,, how do we initialize balance? 13.4 Inheritance and Constructors super(); Calls the default constructor of the superclass Analogous to this() Every constructor of a subclass must make a call to the superclass constructor. If you don t t compiler will add in A call to super( ) MUST be the first line of code in the constructor 7

Checking Account public class CheckingAccount extends BankAccount public CheckingAccount(double initialbalance) // Construct superclass super(initialbalance); // Initialize transaction count transactioncount = 0;... class MyClass public MyClass(int x)... class SubClass extends MyClass //No Constructor Won t t compile default constructor of SubClass tries to call super( ), but MyClass( ( ) is not defined 13.4 Inheritance and Constructors class MyClass public MyClass(int x)... class SubClass extends MyClass public SubClass() super();//invalid! If a class has a superclass that is not the Object class, then a constructor of the class should make an explicit call to a constructor of the superclass. Always provide a constructor for every class you define. Don t t rely on default constructors. class MyClass public MyClass(int x)... class SubClass extends MyClass public SubClass(int y) super(y);//valid! Ok to convert subclass reference to superclass reference (think: BlueJay to Bird) SavingsAccount collegefund = new SavingsAccount(10); BankAccount anaccount = collegefund; Object anobject = collegefund; 8

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 Why is this? Conversions Converting up to superclass leads to less information Why would we want this? Reuse code that uses superclass Reuse code that knows about the superclass but not the subclass: public void transfer(double amount, BankAccount other) withdraw(amount); other.deposit(amount); Super to Sub Conversion Already learned how to use this method to transfer from one BankAccount to another But we can also use it to transfer from one CheckingAccount to another! The method doesn t t know the difference, because it only needs to know that a CheckingAccount IS A BankAccount How do we convert down the chain BankAccount object CheckingAccount? Is this safe? We need a way to protect ourselves if we aren t sure 9

instanceof Purpose: Check to see if an object is of a particular class Give: identifier and class Returns: boolean true if it is that type, false otherwise Convert from super to sub if (anobject( instanceof BankAccount) BankAccount anaccount = (BankAccount( BankAccount) anobject;... 13.6 Polymorphism In Ch.11, we learned that the type of the identifier (Measurable) does not have to match the type of the object (BankAccount( BankAccount,, Coin) Inheritance demonstrates the same phenomenon A BankAccount identifier can be referring to a BankAccount, CheckingAccount,, or SavingsAccount Which version of deposit is called? When is this determined? BankAccount anaccount = new CheckingAccount(); anaccount.deposit(1000); Limitation Method calls are always determined on the type of the actual object being stored,, not the type of the reference/identifier This ability to refer to multiple types with varying behavior is called polymorphism A limitation is that polymorphism only works if the reference type always has an implementation of that call Ex. Will the following work? Measurable x = new BankAccount(); x.deposit(500); 10

Why? Previously, we called deposit on a BankAccount object. When compiling, Java needs to know that a deposit method is legal to call on that object, not which method will be called Even though we didn t t know which version would be called, we can be guaranteed that any object stored with a BankAccount reference can handle deposit If the method is specific to only one subclass, then the compiler can t t guarantee legality Object anobject = new BankAccount(); anobject.deposit(1000); // Compiling Error ------- BankAccount ba = new CheckingAccount(); anobject.deductfees(); // Compiling Error 13.7 Access Control Java has four levels of controlling access to fields, methods, and classes: access public access Can be accessed by methods of all classes private access Can be accessed only by the methods of their own class access protected access Can be accessed by methods of this class and subclasses only See Advanced Topic 13.3 package access The default, when no access modifier is given Can be accessed by all classes in the same package 13.8 Object: The Cosmic Superclass Recall that everything inherits from Object What comes in this class? Most useful methods: String tostring() boolean equals(object otherobject) Object clone() package java.lang; class Object belongs to java.lang package is the superclass of all other classes has several generic methods equals tostring getclass clone Why to these matter? Good idea to override these methods 11

Object Class Methods boolean equals ( Object obj ) returns true if (and only if) this object is alias of obj default: compares addresses String tostring () returns a String representing this object default: <class name>@<hashcode hashcode> 13.8.1 tostring() Going to concentrate on the tostring method Returns a string representation of the object Useful for debugging: Rectangle box = new Rectangle(5, 10, 20, 30); String s = box.tostring(); // Sets s to // "java.awt.rectangle[x" java.awt.rectangle[x=5,y=10,width=20,height=30]" Java insight Unlike other methods, tostring() can actually be called implicitly Concatenation "box = " + box; Calling print() or println() System.out.println(box); How can the compiler know to do this? Because every object has a tostring method through Inheritance polymorphism What does tostring return? The Object class definition returns the object and a hashcode (identifier) BankAccount momssavings = new BankAccount(5000); String s = momssavings.tostring(); // Sets s to something like "BankAccount@d24606bf Pretty boring Overriding tostring() We can override the definition of any inherited method! Usually want to know what s s inside the object (fields, etc) Print name of class, then the values of instance fields in brackets public String tostring() return "BankAccount[balance" BankAccount[balance=" + balance + "]"; 12

More useful version Now this works better: BankAccount momssavings = new BankAccount(5000); String s = momssavings.tostring(); // Sets s to "BankAccount[balance" BankAccount[balance=5000]" Adv 13.4 tostring is a little harder with subclasses How do we make BankAccount tostring work for any subclasses? Use getclass() method public String tostring() return getclass().getname() + "[balance=" + balance + "]"; equals Seen before in the String class Tests that the data in the two objects are the same, not that both reference the same object Version in Object does the same thing as == Testing for equality might have different meanings in different classes (do all the data members need to match, or just certain ones?) So we need to override! public boolean equals(object obj) BankAccount b = (BankAccount)obj( BankAccount)obj; return b.balance == this.balance; Parameter must be of type Object, but we must cast it before we can test the data members It is pretty easy for BankAccount,, with only 1 primitive data member, but gets trickier when data members include arrays and other objects 13