Inheritance (Extends) Overriding methods IS-A Vs. HAS-A Polymorphism. superclass. is-a. subclass

Similar documents
Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

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

INHERITANCE. Spring 2019

Java Object Oriented Design. CSC207 Fall 2014

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

Inheritance. Transitivity

Rules and syntax for inheritance. The boring stuff

ITI Introduction to Computing II

Inheritance and Polymorphism. CS180 Fall 2007

ITI Introduction to Computing II

Java Magistère BFA

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

What is Inheritance?

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

Inheritance (Part 2) Notes Chapter 6

Inheritance (Part 5) Odds and ends

Inheritance and Interfaces

Abstract Classes and Interfaces

Creating an object Instance variables

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

Lecture 18 CSE11 Fall 2013 Inheritance

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

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

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

Practice for Chapter 11

Class definition. complete definition. public public class abstract no instance can be created final class cannot be extended

CMSC 132: Object-Oriented Programming II

Outline. Inheritance. Abstract Classes Interfaces. Class Extension Overriding Methods Inheritance and Constructors Polymorphism.

Basic Principles of OO. Example: Ice/Water Dispenser. Systems Thinking. Interfaces: Describing Behavior. People's Roles wrt Systems

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

The Object Class. java.lang.object. Important Methods In Object. Mark Allen Weiss Copyright 2000

CS-202 Introduction to Object Oriented Programming

Example: Count of Points

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

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

Arrays Classes & Methods, Inheritance

Introduction to Inheritance

Exercise: Singleton 1

OOPs Concepts. 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8.

Inheritance and Polymorphism

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

Lecture 4: Extending Classes. Concept

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

Methods Common to all Classes

Inheritance and Polymorphism

Inheritance (continued) Inheritance

Java Fundamentals (II)

Advanced Placement Computer Science. Inheritance and Polymorphism

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

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

First IS-A Relationship: Inheritance

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

Programming Languages and Techniques (CIS120)

Object Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia

CLASS DESIGN. Objectives MODULE 4

Inheritance -- Introduction

Topic 5 Polymorphism. " Inheritance is new code that reuses old code. Polymorphism is old code that reuses new code.

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

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

1B1b Inheritance. Inheritance. Agenda. Subclass and Superclass. Superclass. Generalisation & Specialisation. Shapes and Squares. 1B1b Lecture Slides

Class Hierarchy and Interfaces. David Greenstein Monta Vista High School

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

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

Chapter 9 Inheritance

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.

Super-Classes and sub-classes

PROGRAMMING LANGUAGE 2

Object-Oriented Concepts

C12a: The Object Superclass and Selected Methods

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

OBJECT ORIENTED PROGRAMMING. Course 4 Loredana STANCIU Room B616

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

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

Object Oriented Programming. Java-Lecture 11 Polymorphism

Example: Count of Points

Instance Members and Static Members

OBJECT ORİENTATİON ENCAPSULATİON

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

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

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

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

C++ Important Questions with Answers

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

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

CS 251 Intermediate Programming Inheritance

Handout 9 OO Inheritance.

More Relationships Between Classes

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

Inheritance. Notes Chapter 6 and AJ Chapters 7 and 8

COS226 - Spring 2018 Class Meeting # 13 March 26, 2018 Inheritance & Polymorphism

public static boolean isoutside(int min, int max, int value)

CS313D: ADVANCED PROGRAMMING LANGUAGE

Inheritance and Polymorphism

COP 3330 Final Exam Review

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

Object-Oriented Programming More Inheritance

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

More about inheritance

Inheritance. The Java Platform Class Hierarchy

Inheritance: Definition

Transcription:

Inheritance and Polymorphism Inheritance (Extends) Overriding methods IS-A Vs. HAS-A Polymorphism Inheritance (semantics) We now have two classes that do essentially the same thing The fields are exactly the same The methods are nearly exactly the same Duplicated code is a bad thing Difficult to maintain all versions in same state More work, period Objects can share functionality by extending another object All fields and methods from the parent class () are automatically copied/available in the child class (). +equals(obj : ) : boolean +clone() : 71 Inheritance (syntax): extends is more basic then Canvas. inherits functionality from (sunclass) extends () The can add new fields/methods The can override methods that it inherits! public ( int x, int y ) { // our constructor code here // end constructor // our code to check valid x here public void sety ( int y ) { // our code to check valid y here // end method sety // end class +clone() : 72 1

Inheritance (syntax): super The inherits all accessible members Private members are not directly accessible If you want to use a s method instead of the es override then you can specify super if (x < 0) {x = 0; if (x > 800) {x = 800; this.x = x; // fails!! x is private // end class if (x < 0) {x = 0; if (x > 800) {x = 800; super.setx(x); +clone(): 73 Inheritance (syntax): protected rror! Hor Good style! A inherits all accessible members protected access modifier: allows full access to es (cool) and all classes in package (horrible!) Style hint: Use super to avoid access modifier protected if (x < 0) {x = 0; if (x > 800) {x = 800; this.x = x; // ok if x is accessible // end class if (x < 0) {x = 0; if (x > 800) {x = 800; super.setx(x); #x #y +clone() : public class { protected int x; protected int y; // end class 74 Inheritance (style): constructors Style: Always explicitly call the constructor as the very first line of the constructor Syntax: There are other valid syntactically correct ways to implement constructors. Avoid them for now! ( int x, int y ) { super(x,y); setx(x); // apply mutators sety(y); // to enforce bounds // end constructor // end class +clone() : 75 2

Inheritance trees You can extend most classes You can extend es No practical limit to depth Most trees are shallow and wide Classes declared final cannot be extended (rare!) Objects call the lowest method from their start in the tree! How many instance variables does each class have? What methods are available to each class? CorporateTrainer promotecorp() : BS teach(): Knowledge Teacher name : String institution : String area: String teach() : Knowledge ClassroomTeacher classsize : int settleclassdown() : BS Professor research() : Knowledge pontificate() : BS ClassroomTeacher Teacher ClassroomTeacher has-a classsize Professor ClassroomTeacher and Teacher 76 Inheritance (style) Look for objects that have common attributes and behaviors: Do they know some of the same things? Do they do some the same things? Design a class the represents the common state and behavior This avoids duplicated code and promotes extendibility! Decide if a needs behaviors (method implementations) that specific to the type Override as needed! Use super to extend methods if appropriate. Look for more opportunities to use abstraction by finding two or more es that might need common behavior Make your tree as wide / deep as necessary. Write out the final class hierarchy as a UML diagram UML is like the blueprint for object design Is-a is unidirectional! Know the direction! Superclasses cannot inherit anything from es! 77 Inheritance (reference summary) A extends as A inherits all public instance variables and methods of the, but does not inherit the private instance variables and methods of the Inherited methods can be overridden; instance variables cannot be overridden Use the IS-A test to verify your inheritance hierarchy. If X extends Y then X IS- A Y must make sense The IS-A relationship only works in one direction. A penguin bird, but not all birds are penguins. When a method is overridden in a, and that method is invoked on an instance of the, the overridden version of the method is called. (The lowest one wins.) Inheritance is transitive. If class B extends class A, and C extends B, class B IS- A class A and class C IS-A class B, and class C also IS-A class A. You get rid of a lot of duplicated code by using inheritence. If you need to change the shared behavior, you just have to update in the. All classes that extend it will automatically use the new version! 78 3

Polymorphism Inheritance buys us two major things (1) You avoid duplicate code (2) You define a common protocol for a set of classes related through inheritance. When you define an inheritable method in a, all objects that extend it must implement that method. They may use the method as-is in the They may override it with their own implementation But they have it This establishes a contract and allows polymorphism (many shapes) An instance of any object is considered to match type with all of its es. Any object that passes the IS-A test with any class can be stored/passed/returned as a reference of that type! 79 Polymorphism in action Teacher smith = new Teacher(); Teacher doom = new Professor(); if ( doom.institution.equals( smith.institution) { Teacher name : String institution : String area: String teach() : Knowledge CorporateTrainer ClassroomTeacher promotecorp() : BS classsize : int teach(): Knowledge settleclassdown() : BS Teacher[] teacherlist; teacherlist = = new Teacher[10]; teacherlist[0] = new Professor(); teacherlist[1] = new CorporateTrainer(); Professor research() : Knowledge pontificate() : BS 80 Polymorphism in action class Room { public void activity(teacher theteacher) { theteacher.teach(); end class activity // end class Room class Main { public static void main(string args) { Room r = new Room(); CorporateTrainer c = new CorporateTrainer(); Professor p = new Professor(); r.activity(c); r.activity(p); // end method main // end class Main CorporateTrainer s overridden teach() runs Professor s inherited teach() runs 81 4

Polymorphism (summary) If you write code using polymorphic arguments (where to declare method parameters as a type) then you can pass in any type at runtime This means that after you write/test your code, you (or anyone else) can add new types to the program and that your existing methods will still work! Similarly, it means that you can extend existing classes (such as library classes) and that all of the library code will work on/with your new class! The methods ARE the contract The method name, return value, and arguments list (number, type, order) of the specified supertype is used during compiletime The method name, return value, and arguments list (number, type, order) of the object type is used during runtime 82 The Object class What makes an object an object? All classes either: explictly extend another class implictily extend Object Class Object is the mother of all classes Class Object is the of all objects Class Object has the default constructor and other default methods The existence of this common allows the creation of routines that (using polymorphism) work on all classes! Consider that you can put objects that you define in an ArrayList! Object +Object() +equals (object : Object) : boolean +tostring () : String +clone(object : Object) : Object +getclass() : Class <?> +hashcode(): int +notify() : void +notifyall(): void +wait() : void +wait(timeout : long) : void +wait(timeout : long, nanos : int) : void 83 instanceof operator How can you determine if a polymorphic object is an instance of a particular class? ArrayList<Teacher> teacherlist = new ArrayList<Teacher>; CorporateTrainer c = new CorporateTrainer(); teacherlist.add(c); Professor p = new Professor(); teacherlist.add(p); add(p); int numprofessors = 0; int numcorporatetrainers = 0; for (Teacher teacher : teacherlist) { if (teacher instanceof Professor) { numprofessors++ if (teacher instanceof CorporateTrainer) { numcorporatetrainers++; 84 5

Some final thoughts final variables: value can t be changed. final public double PI = 3.14; final methods: method can t be overridden final public String tostring() { final class: class can t be extended final public class SmartestPersonInTheWorld { 85 6