Inheritance. CSE 142, Summer 2002 Computer Programming 1.

Similar documents
Interfaces. Readings and References. Recall the discussion of ArrayLists. How can we manage lists of objects? Reading

Interfaces. CSE 142, Summer 2002 Computer Programming 1.

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

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

CSE 142 Su 04 Computer Programming 1 - Java. Objects

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

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

Object Oriented Programming. Java-Lecture 11 Polymorphism

Java Object Oriented Design. CSC207 Fall 2014

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

Today. Book-keeping. Inheritance. Subscribe to sipb-iap-java-students. Slides and code at Interfaces.

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

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

Inheritance Systems. Merchandise. Television Camcorder Shirt Shoe Dress 9.1.1

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

CSE 142 Su 02 Homework 4

Chapter 14 Abstract Classes and Interfaces

ITI Introduction to Computing II

ITI Introduction to Computing II

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

Inheritance CSC9Y4. Inheritance

Inheritance and Polymorphism

ArrayLists. Readings and References. Collections in the Real World. How can we manage lists of objects? Reading. Other References

ArrayLists. CSE 142, Summer 2002 Computer Programming 1.

Rules and syntax for inheritance. The boring stuff

Inheritance and Polymorphism

COMP 250 Fall inheritance Nov. 17, 2017

Object Oriented Programming and Design in Java. Session 10 Instructor: Bert Huang

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

ECE 122. Engineering Problem Solving with Java

First IS-A Relationship: Inheritance

Inheritance & Polymorphism

Accelerating Information Technology Innovation

Definition of DJ (Diminished Java)

AP CS Unit 6: Inheritance Notes

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

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

Abstract Classes and Interfaces

Inheritance (Outsource: )

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

CS-202 Introduction to Object Oriented Programming

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

Example: Count of Points

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

Practice for Chapter 11

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

CREATED BY: Muhammad Bilal Arslan Ahmad Shaad. JAVA Chapter No 5. Instructor: Muhammad Naveed

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber

Inheritance Motivation

Inheritance. Transitivity

CS Programming I: Inheritance

CISC 3115 TY3. C09a: Inheritance. Hui Chen Department of Computer & Information Science CUNY Brooklyn College. 9/20/2018 CUNY Brooklyn College

Basic Object-Oriented Concepts. 5-Oct-17

Object-Oriented Programming More Inheritance

Inheritance (continued) Inheritance

Object-Oriented Programming (Java)

Outline. More optimizations for our interpreter. Types for objects

Inheritance, polymorphism, interfaces

Making New instances of Classes

Logistics. Final Exam on Friday at 3pm in CHEM 102

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

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

ITI Introduction to Computing II

Comp 249 Programming Methodology

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

Introduction to Object-Oriented Programming

Java and OOP. Part 3 Extending classes. OOP in Java : W. Milner 2005 : Slide 1

ITI Introduction to Computing II

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

PowerPoint Slides. Object-Oriented Design Using JAVA. Chapter 2. by Dale Skrien

CS/ENGRD 2110 FALL Lecture 7: Interfaces and Abstract Classes

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

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

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

Some client code. output. subtype polymorphism As dynamic binding occurs the behavior (i.e., methods) follow the objects. Squarer

Java Magistère BFA

Super-Classes and sub-classes

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

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

What is Inheritance?

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

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

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

CS/ENGRD 2110 SPRING 2018

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

CS 251 Intermediate Programming Inheritance

Inheritance, Polymorphism, and Interfaces

Reusing Classes. Hendrik Speleers

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

index.pdf January 21,

Exceptions. CSE 142, Summer 2002 Computer Programming 1.

Exceptions. Readings and References. Exceptions. Exceptional Conditions. Reading. CSE 142, Summer 2002 Computer Programming 1.

22. Inheritance. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

Constructor. Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

OBJECT ORİENTATİON ENCAPSULATİON

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

Written Test 2. CSE Section M, Winter p. 1 of 8. Family Name: Given Name(s): Student Number:

CS111: PROGRAMMING LANGUAGE II

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

Inheritance, and Polymorphism.

Transcription:

Inheritance CSE 142, Summer 2002 Computer Programming 1 http://www.cs.washington.edu/education/courses/142/02su/ 29-July-2002 cse142-14-inheritance 2002 University of Washington 1

Reading Readings and References» Sections 14.1 and 14.2, An Introduction to Programming and Object Oriented Design using Java, by Niño and Hosch Other References» Sections Object-Oriented Programming Concepts and Classes and Inheritance of the Java tutorial» http://java.sun.com/docs/books/tutorial/java/ 29-July-2002 cse142-14-inheritance 2002 University of Washington 2

Relationships between classes Classes can be related via composition» This is often referred to as the has-a relationship» eg, a Car has a list in an ArrayList of Shapes Classes can also be related via inheritance» This is often referred to as the is-a relationship» eg, a Triangle is a PolyShape 29-July-2002 cse142-14-inheritance 2002 University of Washington 3

Composition Vs. Inheritance The has-a relationship is composition The is-a relationship is inheritance Prefer composition to inheritance Beware of inheritance graphs that are either very wide or very deep» very wide means that you are perhaps not abstracting enough at the top layer» very deep means that you are adding only a little functionality at each layer and making fine distinctions that may not survive the test of time 29-July-2002 cse142-14-inheritance 2002 University of Washington 4

Car has a list of Shapes Car ArrayList myshapes int cornerx int cornery int deltay int deltax etc ArrayList int size item 0 item 1 item 2 etc Oval Oval Rectangle 29-July-2002 cse142-14-inheritance 2002 University of Washington 5

Triangle is a PolyShape is a is a is a

Code simplification Why use inheritance?» Avoid doing the same operation in two places» Avoid storing matching state in two places Code simplification» We can deal with objects based on their common behavior, and don t need to have special cases for each subtype Code simplification» Lots of elegant code has already been written - use it, don t try to rewrite everything from scratch 29-July-2002 cse142-14-inheritance 2002 University of Washington 7

Example: Shapes Why use inheritance?» What is some behavior common to all shapes? movement, intersection» What are some attributes common to all shapes? size, location, color We defined behaviors that a Shape must have when we discussed the Shape interface But even with an interface defined, we still need implementations for each method 29-July-2002 cse142-14-inheritance 2002 University of Washington 8

From OvalSlider.java The Shape interface /** the Shape that we are moving around on the screen */ private Shape theshape; OvalSlider doesn t care about the special characteristics of an Oval, it only cares that an Oval can do the things that a good Shape should be able to do void addto(gwindow gw) Rectangle getboundingbox() int getcenterx() int getcentery() java.awt.color getcolor() int getheight() int getwidth() int getx() int gety() uwcse.graphics.internalgwindow currentwindow() boolean intersects(shape other) void moveby(int deltax, int deltay) void moveto(int x, int y) void paint(java.awt.graphics g) void recordwindow(uwcse.graphics.internalgwindow gw) void removefromwindow() void rotatearound(int pivotx, int pivoty, double degrees) void setcolor(java.awt.color c) 29-July-2002 cse142-14-inheritance 2002 University of Washington 9

Why use inheritance? Sometimes it takes several levels of abstraction to get to concrete objects» a Triangle is a PolyShape, which is a ShapeImpl, which is an Object. At each of these levels, there might be behavior to factor out or abstract away. All Shapes must implement similar methods» we want to do int x = blob.getx()» if both Triangles and Ovals implement this the same way, we can implement getx() in one base class, and use it in the subclasses instead of rewriting it each time 29-July-2002 cse142-14-inheritance 2002 University of Washington 10

Triangle constructors and methods

Syntax of inheritance Specify inheritance relationship using extends» this is just like we did with interfaces public class Triangle extends PolyShape { public abstract class PolyShape extends ShapeImpl { private int npoints; public abstract class ShapeImpl implements Shape { protected Rectangle boundingbox; public int getx() { return boundingbox.getx(); 29-July-2002 cse142-14-inheritance 2002 University of Washington 12

Reduce the need for duplicated code Remember our collection of pets?» Dog has getmealsize() and eat(double w) methods» Cat has getmealsize() and eat(double w) methods» and they are implemented exactly the same way We can define a class named BasicAnimal that implements these methods once, and then the subclasses can extend it and add their own implementations of other methods if they like 29-July-2002 cse142-14-inheritance 2002 University of Washington 13

BasicAnimal class 29-July-2002 cse142-14-inheritance 2002 University of Washington 14

Dog as a subclass of BasicAnimal 29-July-2002 cse142-14-inheritance 2002 University of Washington 15

Using the superclass constructor Constructor of the superclass is called to do much (or all) of the initialization for the subclass public class Dog extends BasicAnimal { public Dog(String thename) { super(thename,0.5,20); public Dog(String thename,double serving,double weight) { super(thename,serving,weight); public class BasicAnimal implements Animal { public BasicAnimal(String thename,double serving,double weight) { name = thename; mealsize = serving; currentweight = weight; System.out.println("Created "+name); 29-July-2002 cse142-14-inheritance 2002 University of Washington 16

this() and super() as constructors You can use an alias to call another constructor» super(...) to call a superclass constructor» this( ) to call another constructor from same class The call to the other constructor must be the first line of the constructor» If neither this() nor super() is the first line in a constructor, a call to super() is inserted automatically by the compiler. This call takes no arguments. If the superclass has no constructor that takes no arguments, the class will not compile. 29-July-2002 cse142-14-inheritance 2002 University of Washington 17

Overriding methods Overriding methods is how a subclass refines or extends the behavior of a superclass method Manager and Executive classes extend Employee How do we specify different behavior for Managers and Executives?» Employee: double pay() {return hours*rate + overtime*(rate+5.00);» Manager: double pay() {return hours*rate;»executive: double pay() {return salary + bonus; 29-July-2002 cse142-14-inheritance 2002 University of Washington 18

Overriding methods public class Employee { // other stuff public float pay() { return hours*rate + overtime*(rate+5.00); public class Manager extends Employee { // other stuff public float pay() { return hours*rate; 29-July-2002 cse142-14-inheritance 2002 University of Washington 19

Overriding rules A method cannot be made more private than the superclass method it overrides // in superclass public void pay() {... // in subclass public void pay() {... // valid private void pay() {... // invalid 29-July-2002 cse142-14-inheritance 2002 University of Washington 20

Overriding rules A method s return type and parameters must match those in the overridden superclass method exactly in order to override it. // in superclass public int pay(int hours) { // in subclass public int pay(int b) { public long pay(int b) { // okay, overrides // compile error 29-July-2002 cse142-14-inheritance 2002 University of Washington 21

instanceof Used to test an object for class membership if (bunch.get(i) instanceof Dog) { Good way to ensure that a cast will succeed Tests for a relationship anywhere along the hierarchy» Also tests whether a class implements an interface What class must <classname> represent for the following expression to be true always? if (v instanceof <classname>) { 29-July-2002 cse142-14-inheritance 2002 University of Washington 22

instanceof example with interface ArrayList onstage = thestage.getactors(); for (int i=0; i<onstage.size(); i++) { if (onstage.get(i) instanceof ClickableActor) { ClickableActor clickee = (ClickableActor)onStage.get(i); if (clickee.intersects(cursor)) { clickee.doclickaction(thestage); if (clickee == runbutton) { if (runbutton.isenabled()) { thestage.animate(); else { thestage.quitanimation(); 29-July-2002 cse142-14-inheritance 2002 University of Washington 23