Inheritance & Polymorphism

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

type conversion polymorphism (intro only) Class class

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

More Relationships Between Classes

Programming in C# Inheritance and Polymorphism

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

Java Inheritance. Written by John Bell for CS 342, Spring Based on chapter 6 of Learning Java by Niemeyer & Leuck, and other sources.

What is Inheritance?

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

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

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

CS 251 Intermediate Programming Inheritance

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

First IS-A Relationship: Inheritance

CIS 110: Introduction to computer programming

More On inheritance. What you can do in subclass regarding methods:

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

Inheritance -- Introduction

Exercise: Singleton 1

Lecture 4: Extending Classes. Concept

Rules and syntax for inheritance. The boring stuff

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

Name of subject: JAVA PROGRAMMING Subject code: Semester: V ASSIGNMENT 1

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

Inheritance. Transitivity

Relationships Between Real Things CSC 143. Common Relationship Patterns. Composition: "has a" CSC Employee. Supervisor

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

The class Object. Lecture CS1122 Summer 2008

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

Inheritance (Outsource: )

Inheritance and Polymorphism

Binghamton University. CS-140 Fall Dynamic Types

Example: Count of Points

Announcement. Agenda 7/31/2008. Polymorphism, Dynamic Binding and Interface. The class will continue on Tuesday, 12 th August

Lecture 2 and 3: Fundamental Object-Oriented Concepts Kenneth M. Anderson

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

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

ITI Introduction to Computing II

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

CS260 Intro to Java & Android 03.Java Language Basics

Classes and Inheritance Extending Classes, Chapter 5.2

COMP 110/L Lecture 19. Kyle Dewey

Object Oriented Programming. Java-Lecture 11 Polymorphism

Polymorphism and Inheritance

ITI Introduction to Computing II

COMP 250 Fall inheritance Nov. 17, 2017

Introduction to Object-Oriented Programming

CS100J, Fall 2003 Preparing for Prelim 1: Monday, 29 Sept., 7:30 9:00PM

Introduction to Programming Using Java (98-388)

Inheritance and Polymorphism. CS180 Fall 2007

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

Polymorphism. Arizona State University 1

CLASS DESIGN. Objectives MODULE 4

CO Java SE 8: Fundamentals

Class Hierarchy and Interfaces. David Greenstein Monta Vista High School

Example: Count of Points

Lecture 36: Cloning. Last time: Today: 1. Object 2. Polymorphism and abstract methods 3. Upcasting / downcasting

AP CS Unit 6: Inheritance Notes

Java Object Oriented Design. CSC207 Fall 2014

Java Magistère BFA

COP 3330 Final Exam Review

Programming Exercise 14: Inheritance and Polymorphism

Programming Techniques

Inheritance, polymorphism, interfaces

Informatik II. Tutorial 6. Mihai Bâce Mihai Bâce. April 5,

CSC207H: Software Design. Java + OOP. CSC207 Winter 2018

Abstract Classes and Interfaces

Implements vs. Extends When Defining a Class

Inheritance, Polymorphism, and Interfaces

Objects and Iterators

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

CSCI 355 Lab #2 Spring 2007

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

Review: Object Diagrams for Inheritance. Type Conformance. Inheritance Structures. Car. Vehicle. Truck. Vehicle. conforms to Object

CSC207H: Software Design. Java + OOP. CSC207 Winter 2018

Object Fundamentals Part Three. Kenneth M. Anderson University of Colorado, Boulder CSCI 4448/6448 Lecture 4 09/06/2007

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

CS 1316 Exam 1 Summer 2009

Types. What is a type?

Super-Classes and sub-classes

Inheritance and Polymorphism

ECE 122. Engineering Problem Solving with Java

CSCI 355 LAB #2 Spring 2004

Java How to Program, 8/e

CS-202 Introduction to Object Oriented Programming

Check out Polymorphism from SVN. Object & Polymorphism

CS111: PROGRAMMING LANGUAGE II

Informatik II Tutorial 6. Subho Shankar Basu

This week. Tools we will use in making our Data Structure classes: Generic Types Inheritance Abstract Classes and Interfaces

CS111: PROGRAMMING LANGUAGE II

Binghamton University. CS-140 Fall Chapter 9. Inheritance

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

Computer Science 225 Advanced Programming Siena College Spring Topic Notes: Inheritance

Topic 10. Abstract Classes. I prefer Agassiz in the abstract, rather than in the concrete.

Chapter 14 Abstract Classes and Interfaces

Programming II (CS300)

COMP 401 INHERITANCE: IS-A. Instructor: Prasun Dewan

CS107 Handout 37 Spring 2007 May 25, 2007 Introduction to Inheritance

Inheritance and Interfaces

Transcription:

E H U N I V E R S I T Y T O H F R G E D I N B U Murray Cole

Classifying Things 1 Hierarchies help us to classify things and understand their similarities and differences Some aspects are common to everything at some level Some aspects don t make sense in all categories Some aspects are inherited implicitly from higher levels

Manipulating Things 2 Similarly, build operations on our classifications at different levels getname on any lobster might return A Lobster getname on a particular pet cat might return Tiddles the Cat getname can be applied to any animal (it is generic), but may behave differently on some sub-categories (it can be specialised)

Inheritance 3 This also applies to the things we want to model (with classes) in our programs We could (dangerously!) write the details afresh for each new class cut & paste the bits which are shared Much better, let the language do the work with inheritance and overriding

Objects and the class hierarchy 4 Classes in an object-oriented programming language such as Java are organised into a hierarchy. In the Java class hierarchy we have Object at the root, meaning that every class which we define is a subclass of Object. Below Object we have Boolean, Character, Number, Color, Polygon and many, many others. Beneath Number we have Byte, Short, Integer, Long, Float and Double.

5 The Class Hierarchy Object Number Character Color Polygon Boolean Byte Short Integer Long Float Double

Superclasses and inheritance 6 We refer to the parent of a class as its superclass. Classes inherit from their superclass (and from its superclass... ) We can think of inheritance as an is-a relationship. An Integer is a Number. A Horse is a Mammal. The class Object defines methods such as equals() and tostring() so we know that objects of any subclass of Object (and so of any class) can be tested for equality or converted to a String representation.

Extending the Hierarchy by Subclassing 7 A class declaration can include the phrase extends class CompSciStudent extends Student { public String username; public int diskquota; } As well as new fields, a subclass may add new methods Or a subclass may replace methods of its superclass with its own versions, which is called method overriding.

When overriding is useful 8 Imagine we extend the Student class to include a method for sending a message to the student s DOS. class Student { public void senddosnote(string msg) { // send note to DOS using internal mail InternalMail.sendLetter(this.dos.address,msg); } }

When overriding is useful, II 9 For a CS student (who has a DOS in CS), there is a better way of sending a message, using email. So we override the senddosnote method. class CompSciStudent extends Student {... public void senddosnote(string msg) { // send email to DOS, should be reliable UnivEmail.sendEmail(this.dos.email,msg); }

Collection classes 10 The collection classes in Java are defined to be able to store instances of Object. This means that we can store a mixed bag of objects as a collection (a heterogeneous collection). In other programming languages collections are usually constrained to store only a single kind of object (a homogeneous collection).

Methods of the Vector class 11 Vector() This is the constructor of the class, as usual. We create a new Vector with Vector v = new Vector(); addelement() This method adds an object to the vector. We would invoke it to add the String value "abc" as v.addelement("abc"); We could then follow this with a Date object with v.addelement(new Date()); removeelement() We can remove a given element with this method. For example, v.removeelement("abc"); elementat() We can inspect the object stored at a particular location by supplying an integer index into the vector.

Methods of the Vector class 12 insertelementat() We can insert an element into the vector at any position. For example, the method invocation v.insertelementat("def", 0); will insert the String "def" at position zero in the vector. setelementat() Vectors are updateable so we could overwrite the string stored at location zero with another like this: v.setelementat("ghi", 0); iterator() We can examine all of the elements of the vector by asking for them to be supplied as an Iterator.

Polymorphism 13 Vectors are a polymorphic data structure ( polymorphic = having many forms ). This means that the same operations can be used for vectors of integer objects as for strings or whatever. In contrast, many programming languages only support only the definition of monomorphic data structures ( monomorphic = having only one form ). In a monomorphic programming language separate implementations of the vector operations would be needed for each kind of vector. The use of a single definition which is re-usable at different types (i.e. polymorphic) saves effort and reduces the chance of error.

Processing objects by type 14 When we retrieve objects from a collection we need to restore the class which they had before they were coerced to Object. Casting up the class hierarchy, an operation which is sometimes called widening, is always safe (every Integer is a Number... ). However, casting down the class hierarchy (narrowing), is not always safe (not every Number is an Integer... ). If we get this down-casting wrong the operation will fail at run-time with a ClassCastException. We can investigate the class of an object at run-time by the use of the instanceof relation.

static void countandprint (Vector v) { Iterator i = v.iterator(); int stringcount = 0; int inttotal = 0; while (i.hasnext()) { Object o = i.next(); if (o instanceof String) stringcount++; else if (o instanceof Integer) { Integer n = (Integer) o; inttotal += n.intvalue(); } } System.out.println("Strings: " + stringcount); System.out.println("Integer total: " + inttotal); } 15