Outline. 15. Inheritance. Programming in Java. Computer Science Dept Va Tech August D Barnette, B Keller & P Schoenhoff

Similar documents
Inheritance and Polymorphism

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

Full file at Chapter 2 - Inheritance and Exception Handling

Inheritance, Polymorphism, and Interfaces

CSCI-142 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community

Inheritance -- Introduction

More on Objects in JAVA TM

Java Fundamentals (II)

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

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.

Building custom components IAT351

PIC 20A Streams and I/O

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

Computer Science 2 Lecture 4 Inheritance: Trinidad Fruit Stand 02/15/2014 Revision : 1.7

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Encapsulation. Inf1-OOP. Getters and Setters. Encapsulation Again. Inheritance Encapsulation and Inheritance. The Object Superclass

Example: Count of Points

Inf1-OOP. Inheritance and Interfaces. Ewan Klein, Perdita Stevens. January 12, School of Informatics

Programming II (CS300)

I/O streams. Byte Streams Character Streams InputStream ByteArrayInputStream FileInputStream FilterInputStream

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

CS-202 Introduction to Object Oriented Programming

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

Polymorphism. return a.doublevalue() + b.doublevalue();

Software Paradigms (Lesson 3) Object-Oriented Paradigm (2)

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

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

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L

Inf1-OP. Classes with Stuff in Common. Inheritance. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein.

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

Java Object Oriented Design. CSC207 Fall 2014

M301: Software Systems & their Development. Unit 4: Inheritance, Composition and Polymorphism

Inf1-OP. Inheritance. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein. March 12, School of Informatics

CS313D: ADVANCED PROGRAMMING LANGUAGE

Inheritance (continued) Inheritance

Binghamton University. CS-140 Fall Problem Solving. Creating a class from scratch

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

Chapter 7. Inheritance

Chapter 14 Abstract Classes and Interfaces

Lecture 11.1 I/O Streams

Chapter 12: Inheritance

What is Inheritance?

Rules and syntax for inheritance. The boring stuff

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

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

Special error return Constructors do not have a return value What if method uses the full range of the return type?

First IS-A Relationship: Inheritance

CSC9T4: Object Modelling, principles of OO design and implementation

CLASS DESIGN. Objectives MODULE 4

C++ Important Questions with Answers

Object Oriented Design. Object-Oriented Design. Inheritance & Polymorphism. Class Hierarchy. Goals Robustness Adaptability Flexible code reuse

Language Features. 1. The primitive types int, double, and boolean are part of the AP

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and More

Java Magistère BFA

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

Chapter 5 Object-Oriented Programming

CMSC 132: Object-Oriented Programming II

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

Object-Oriented Design. March 2005 Object Oriented Design 1

Systems programming. Object Oriented Programming. I. Object Based Programming II. Object Oriented Programming

Instance Members and Static Members

Methods Common to all Classes

Object Oriented Programming. I. Object Based Programming II. Object Oriented Programming

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Making New instances of Classes

Object Oriented Programming Part II of II. Steve Ryder Session 8352 JSR Systems (JSR)

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

Polymorphism and Inheritance

COMP200 INTERFACES. OOP using Java, from slides by Shayan Javed

Aggregation. Chapter 8. Java By Abstraction Chapter 8. Outline. 8.1 What is Aggregation? Copyright 2006 Pearson Education Canada Inc.

CLASSES AND OBJECTS IN JAVA

CONSTRUCTOR & Description. String() This initializes a newly created String object so that it represents an empty character sequence.

Super-Classes and sub-classes

Inheritance and Interfaces

OBJECT ORIENTED PROGRAMMING. Course 4 Loredana STANCIU Room B616

Java for Non Majors Spring 2018

Inheritance (Part 5) Odds and ends

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

Abstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes.

Practice for Chapter 11

CS260 Intro to Java & Android 03.Java Language Basics

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

8. Polymorphism and Inheritance

More about inheritance

Relationships Between Real Things CSE 143. Common Relationship Patterns. Employee. Supervisor

Inheritance. Transitivity

Lab 2: File Input and Output

CMSC 132: Object-Oriented Programming II. Inheritance

BM214E Object Oriented Programming Lecture 8

CS/ENGRD 2110 FALL Lecture 5: Local vars; Inside-out rule; constructors

Unit3: Java in the large. Prepared by: Dr. Abdallah Mohamed, AOU-KW

CSC 1214: Object-Oriented Programming

Inheritance, polymorphism, interfaces

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Chapter 11 Inheritance and Polymorphism. Motivations. Suppose you will define classes to model circles,

Relationships Between Real Things. CSE 143 Java. Common Relationship Patterns. Composition: "has a" CSE143 Sp Student.

INHERITANCE. Spring 2019

Inheritance. Chapter 7. Chapter 7 1

BBM 102 Introduction to Programming II Spring Inheritance

Transcription:

Outline 1 Inheritance: extends ; Superclasses and Subclasses Valid and invalid object states, & Instance variables: protected Inheritance and constructors, super The is-a vs. has-a relationship (Inheritance vs. Composition) Class hierarchies & the Object class Overriding vs. Overloading Polymorphism Factoring out Common Behavior Abstract methods and classes Interfaces: implements

Inheritance In real life, hierarchies of classes exist. 2 mycar is just as easily a member of the Ford class as the Automobile class Class Automobile Customer Class Ford CorporateCustomer object mycar radioshack

Inheritance: extends This relationship is supported in Java by inheritance. made possible by the extends keyword. 3 class Ford extends Automobile{......... Original class (Automobile) is the Base class. Newly defined class (Ford) is the Derived class. Base class must exist to make a Derived class.

Inheritance 4 Derived classes inherit all data from the Base class. Derived classes inherit all the method interfaces from the Base class, but may specify a new implementation. Derived classes may also add new methods. The Base class is referred to as super Base class = superclass; Derived class = subclass

Inheritance: BetterBR Example.1 5 BetterBR Want to create a BufferedReader from a file name without having to worry about code for the InputStreamReader, FileInputStream, and File classes. Want to be able to read an int as easily as we read a String. The user-defined BetterBR class extends the Java BufferedReader class BetterBR objects are also BufferedReader objects BetterBR objects can be used the same as BufferedReader objects

Inheritance : BetterBR Example.2 6 class BetterBR extends BufferedReader{ public BetterBR(String filename) throws IOException { super(new InputStreamReader( super invokes the base class constructor. new FileInputStream( new File(filename)))); public BetterBR() throws IOException { super(new InputStreamReader(System.in));............. If a derived class has additional data members then their initialization should take place after the invocation of the super constructor.

Inheritance : BetterBR Example.3............. 7 public int readint() throws Exception { string line; line = readline(); Why can we do this? return Integer.parseInt(line); readint() is a BetterBR method, but not a BufferedReader method.

Inheritance : BetterBR Example.4 8 main (String[] arg) throws Exception{ int i; String s; BetterBR bbr = new BetterBR( junk.txt ); i = bbr.readint(); while ( i >= 0) { System.out.println( i = + i); i = bbr.readint(); s = bbr.readline(); while ( s!= null ) { System.out.println( s = + s); s = bbr.readline(); 3 5 237-1 A line Line #2 Last line

Object States 9 A Derived class inherits, (takes on), the data members (instance variables) of the Base class. The data members define an object s state. A derived class may include (extend) additional data (and function) members.

Object States: ExtendedName Eg.1 10 class Name { private String firstname, lastname, title; public Name(String first, String last){ firstname = first; lastname = last; title = ; // ================================================ class ExtendedName extends Name{ private String middlename; How does ExtendedName s constructor ensure a valid state for Name? public ExtendedName(String firstname, String middlename, String lastname){? super(firstname, lastname); this.middlename = middlename; What does this do?

Object States : ExtendedName Eg.2 A two-parameter constructor: 11 public ExtendedName(String firstname, String lastname) { super(firstname, lastname); middlename = ;// this.middlename = ; How does this constructor ensure a valid state?

Object States : ExtendedName Eg.3 12 A derived class s methods should never put the base class in an invalid state. A valid state is: Meaningful in the base class Possible in the base class Invalid state public ExtendedName(String firstname, String middlename, String lastname){ super(, ); middlename = ; The above code would place the inherited base class instance variables in an invalid state because the base class constructors never specified empty string states.

Object States & Access 13 Inherited class may need to directly access the private instance variables in the base class! Private members of the base class may not be directly accessed by derived classes. How can you protect your original class from being corrupted by client code, but still allow derived class code to access/modify base class instance variables? Accessor and mutator methods could be provided, but they may be inappropriate for client code invocation. Some data members should be able to be changed by derived class code, but not by client class code? Solution: protected keyword

Object Access 14 Three ways to classify accessibility of class members: private, public, protected Protected members in the Base class are private in the Derived class Private members in the Base class are inaccessible in the Derived class, even to the methods of the Derived class. Public members in the Base class are public in the Derived class

Object states class Name { protected String firstname, lastname, title; 15 public Name(String first, String last){ firstname = first; lastname = last; // ================================================ class ExtendedName extends Name { private String middlename; public ExtendedName(String firstname, String middlename, String lastname){ super(firstname, lastname); title = ; //base member access this.middlename = middlename;

Object states 16 Which should you use in a base class? private, public, protected Some people think all base class data should be private Then the derived class can t possibly invalidate the base class! Others think all base class data should be protected Makes it easy to do what you want with the derived class Comparison: In base In derived public protected private Works like public Works like public Works like private Works like public Works like private inaccessible

Constructors 17 When a derived class s constructor is called: Room is reserved for all the data members of both the derived class and its base class in the same object. The base class data gets set up then the derived class data gets set up. Derived class constructor must pass needed info to the base class constructor: super(); firstname lastname title middlename

is-a vs. has-a 18 Is-a An object of a derived class is an object of the base class In the left picture, a is a Has-a This is how we ve programmed up until now. In the right picture, a has a

is-a vs. has-a 19 The is-a relationship is called inheritance The has-a relationship is called composition (aggregation) class Name2 { public Name2( String firstname, String middlename, String lastname ){... private Name n; private String middlename; What are some disadvantages to composition?

When to use Inheritance 20 If all methods of the original class X should be methods of the new class Y, then use inheritance. If some of the methods of the original class X should be methods of the new class Y, then use composition. If it feels right to say that a Y is an X (as in a part-timer is an employee ), then use inheritance. If it feels right to say that a Y has an X (as in an employee has a name ), then use composition.

Don t make this mistake: class Name { public String firstname, lastname; public Name (String f, String l){...; 21 /***********************************************/ class ExtendedName extends Name { public String firstname, lastname, middlename; public ExtendedName (String f, String m, String l){...; What s wrong here?

The Object class 22 We ve used the Object class many times. Vectors store only type object. An Object is the very first, basic class defined by Java. Every class implicitly inherits from the Object class (either directly or indirectly). It has some specific methods you can re-define (or override). Some are: boolean equals(object other) String tostring( )

Class hierarchies in Java Both of these are possible: Title could be moved from the base Name class since not all names have a title. Name 23 Name ExtendedName ExtendedName SuffixedName Two subclasses for 1 superclass SuffixedName Subclasses extended to another subclass

Overriding 24 When a method is defined in a base class, it may be overridden (redefined differently) in the derived class. Technique: 1) override a method in a derived class, (i.e. provide an implementation of a base class function in the derived class) 2) create an object of the derived type 3) invoke the overridden method Whether the object is cast as the base type or derived type, the derived method s implementation is used. Don t confuse this with overloading Overloading: writing 2 methods in one class with the same name, differing by parameter lists.

Overriding 25 class Name{ public String getinitials(){ return fname.substring(0,1) +. +... lname.substring(0,1) +. ; /***********************************************/ class ExtendedName extends Name{ public String getinitials(){ return fname.substring(0,1) +. + getmiddleinitial() +. +... lname.substring(0,1) +. ;

Definition: Polymorphism 26 Polymorphism, in programming, is the ability to write code that is independent of the exact type of objects upon which it is executing. Polymorphic code is general code that only relies upon the common properties of objects in an inheritance hierarchy. General polymorphic code treats all objects of an inheritance hierarchy as base class objects. Polymorphism depends on inheritance and overriding. An object of the subclass can be referred to as an object of the superclass. When an overridden method is invoked upon an object reference of the superclass, the body of the subclass s overridden method is executed, (not the base class implementation).

Polymorphism: simple example 27 Vector v; Name n = new Name( Bill, Clinton ); v.add(n); ExtendedName en = new ExtendedName( George, W, Bush ); v.add(en); /**********************************************/ At this point, we don t know (or care) what kind of Name is being referenced! for(int I=0; I < v.size(); I++){ String s = ( (Name) v.elementat(i) ).getinitials(); System.out.println(s); B.C. G.W.B.

Overriden Base Member Invocation 28 A derived class over-riding function may invoke the base class version by use of the super keyword class Name{ public void print(){ system.out.print( lastname +, + firstname);... /***********************************************/ class ExtendedName extends Name{ public void print(){ super.print(); //invoke base class version system.out.print(, + middlename);...

Do you understand? 29 Explain the difference between overloading and overriding Explain the difference between inheritance and polymorphism Explain the difference between base and derived What 3 things must we have in order for these concepts to be useful? Where is the Object class in the Java hierarchy? Why would you want to do any of this? Give examples.

Applets Applet classes inherit from the Applet class Powerful set of GUI tools / window management. 30 class mywebprogram extends Applet{ /******/

Factoring out Common Behavior 31 When designing a set of classes with some commonality, look for their common behavior Example: camera store sells: Lenses focal length, zoom capability (Boolean) Film storage temperature, # exposures Cameras w/lens(bool), shutter speed, body color... But all of them have: Description, quantity on hand, price, inventory number

Factoring out Common Behavior class InventoryItem{ InventoryItem( ){ // constructor String getdescription(){return desc; int getquantityonhand(){return qoh; int getprice(){return price; 32 String desc; // description int inventorynumber; int qoh; // quantity on hand int price;

Factoring out Common Behavior 33 class Lens extends InventoryItem{ Lens( ){ // constructor super( ); /* other code */ /* METHODS SPECIFIC TO LENS*/ boolean iszoom(){return zoom; double getfocallength(){return focallength; /* INSTANCE VARIABLES SPECIFIC TO LENS*/ boolean zoom; double focallength;

Abstract methods & classes 34 A base class doesn t have to define all its methods! It can simply provide a prototype. If any method in a class doesn t have an implementation, it is an abstract method. Any class with an abstract method is an abstract class. An abstract class cannot be instantiated. (You cannot create an object of that type.) Why are abstract classes useful then?

Abstract methods & classes 35 Suppose you want to print out your camera store inventory items. All items will be stored in the same vector, so when you getnextelement(), you won t know whether you have a lens, camera, or film. You could provide a method in InventoryItem called print(), and then override it in all subclasses But what would the body of InventoryItem.print() look like? You can t define it, because the info you print depends on the type of item.

Abstract methods & classes 36 abstract class InventoryItem{ public InventoryItem(){ // etc. abstract public void print(); // no body! // other stuff /**********************************/ class Lens extends InventoryItem{ void public print(){ if (zoom) System.out.printLn( Zoom ); System.out.println( Lens ); // other stuff

Abstract classes 37 Another example is the InputStream class. InputStream is abstract. You cannot instantiate it directly. But there are several derived classes which you can instantiate. StringBufferInputStream, FileInputStream, and FilterInputStream InputStreamReader s constructor requires an InputStream argument. We can give InputStreamReader an object from any derived class. Each derived class works differently, but InputStreamReader never needs to know what type of InputStream it has!

Interfaces 38 Sometimes you need to specify generic behavior for a group of classes that are not related in any obvious hierarchical way. Example: the Enumeration type. Suppose you add another inventory item to your camera store: a package deal, including a camera, several lenses, and several rolls of film. Your class must inherit from your InventoryItem class, for obvious reasons. But let s say you also want it to work as an Enumeration type spitting out one of the packaged items at a time.

Interfaces 39 Fortunately, Enumeration is not a class it s an interface. It has no method bodies, just prototypes. It is not a class. interface Enumeration{ Object nextelement(); boolean hasmoreelements();

The implements keyword class PackageDeal extends InventoryItem implements Enumeration{ 40 private Vector packageditems; public PackageDeal( ){ // etc... Object nextelement(){ boolean hasmoreelements(){

The implements keyword 41 Now, if you had a method that took an Enumeration and wrote out the contents myutils.writeenum(e, System.out); You could pass it your PackageDeal objects and it would do the same thing. myutils.writeenum(mypd, System.out);

The implements keyword 42 class myutils{ public static void writeenum(enumeration e, PrintStream output){ String s; while ( e.hasmoreelements() ){ s = e.nextelement().tostring(); output.println(s); tostring() inherited from Object class