Chapter 9 Inheritance

Similar documents
CSE1720. General Info Continuation of Chapter 9 Read Chapter 10 for next week. Second level Third level Fourth level Fifth level

Chapter 10 Collections

Java Object Oriented Design. CSC207 Fall 2014

CS-202 Introduction to Object Oriented Programming

Object. OutputStream write(int) write(byte[]) write(byte[], int, int) FilterOutputStream write(int) write(byte[]) write(byte[], int, int)

COP 3330 Final Exam Review

Chapter 5. Inheritance

1 Shyam sir JAVA Notes

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

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

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

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

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

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

Object Oriented Programming. Java-Lecture 11 Polymorphism

Programming in Java, 2e Sachin Malhotra Saurabh Choudhary

CMSC 132: Object-Oriented Programming II

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

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

Inheritance (continued) Inheritance

Inheritance, Polymorphism, and Interfaces

Rules and syntax for inheritance. The boring stuff

Abstract Classes Interfaces CSCI 201 Principles of Software Development

Abstract Classes Interfaces CSCI 201 Principles of Software Development

Class, Variable, Constructor, Object, Method Questions

What is Inheritance?

Super-Classes and sub-classes

CISC370: Inheritance

Introduction to Inheritance

Check out Polymorphism from SVN. Object & Polymorphism

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

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

CSSE 220 Day 15. Inheritance. Check out DiscountSubclasses from SVN

8. Polymorphism and Inheritance

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

INHERITANCE. Spring 2019

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

CST242 Object-Oriented Programming Page 1

Java Magistère BFA

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

First IS-A Relationship: Inheritance

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

Computer Science 210: Data Structures

CLASS DESIGN. Objectives MODULE 4

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

All classes in a package can be imported by using only one import statement. If the postcondition of a method is not met, blame its implementer

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

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

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

OBJECT ORİENTATİON ENCAPSULATİON

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

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

Polymorphism 2/12/2018. Which statement is correct about overriding private methods in the super class?

Binghamton University. CS-140 Fall Chapter 9. Inheritance

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

The major elements of the object-oriented model

OVERRIDING. 7/11/2015 Budditha Hettige 82

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

Inheritance and Polymorphism

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

CS260 Intro to Java & Android 03.Java Language Basics

Making New instances of Classes

More Relationships Between Classes

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

Inheritance. Notes Chapter 6 and AJ Chapters 7 and 8

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

CS 251 Intermediate Programming Inheritance

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

Example: Count of Points

Inheritance and object compatibility

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber

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

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

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

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

What are the characteristics of Object Oriented programming language?

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

CS1150 Principles of Computer Science Objects and Classes

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

Polymorphism and Interfaces. CGS 3416 Spring 2018

ITI Introduction to Computing II

CS-140 Fall 2017 Test 1 Version Practice Practice for Nov. 20, Name:

Java Fundamentals (II)

CMSC 132: Object-Oriented Programming II

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

VIRTUAL FUNCTIONS Chapter 10

Abstract Classes and Interfaces

Practice for Chapter 11

COE318 Lecture Notes Week 8 (Oct 24, 2011)

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity.

CH. 2 OBJECT-ORIENTED PROGRAMMING

Inheritance. Inheritance

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

AP CS Unit 6: Inheritance Notes

Advanced Placement Computer Science. Inheritance and Polymorphism

CIS 110: Introduction to computer programming

Java. Classes 3/3/2014. Summary: Chapters 1 to 10. Java (2)

ITI Introduction to Computing II

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

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

Transcription:

Chapter 9 Inheritance I. Scott MacKenzie 1 Outline 2 1

What is Inheritance? Like parent/child relationships in life In Java, all classes except Object are child classes A child class inherits the attributes (fields, methods) of its parent class A child class may use the fields and methods of a parent class as though they were defined in the child class itself A child class may itself have a child class (i.e., like parent/child/grandchild relationships in life) 3 Terminology A parent class is also called a superclass A child class is also called a subclass 4 2

Inheritance UML Diagrams (1) Parent class C is a P Child class 5 Inheritance UML Diagrams (2) Parent class Child class Parent class Child class 6 3

Inheritance UML Diagrams (3) 7 Method Section of API Methods defined in this class Methods defined in a parent class 8 4

Methods in a Child Class Methods in a child class are either... New Defined in the class itself, Inherited Defined in a parent class, Overriding Defined in a parent class, but re-defined ( overridden ) in the child class, or Overloading Defined in a parent class, but re-defined with a different signature ( overloaded ) in the child class 9 Child With Three Methods 10 5

RewardCard API 11 Inherited Fields 12 6

Fields in a Child Class Fields in a child class are either... New Defined in the class itself, Inherited Defined in a parent class, or Shadowed Defined in a parent class, but re-defined ( shadowed ) in the child class 13 Child With Two Fields 14 7

Fields in RewardCard Class 15 Inheritance Chains A class may be a subclass of another class, which in turn is a subclass of another class, and so on These are called inheritance chains A typical example is the JButton class in the javax.swing package... Last slide on Mar 8 View API for details 16 8

Polymorphism When using classes and subclasses, it is sometimes not known until runtime which subclass to use E.g., we might wish to create a credit card object without knowing whether it is an ordinary card or a rewards card That s OK. A RewardCard is a CreditCard, so the following makes sense CreditCard card = new RewardCard(123456, John Smith ); Furthermore, we can say that anywhere a CreditCard object is expected, a RewardCard object can be used This is called polymorphism (the ability of one thing to assume different forms) 17 instanceof operator (1) To determine if a CreditCard reference points to a RewardCard object, use Java s instanceof operator, for example... CreditCard card = new RewardCard(123456, John Smith ); IO.println(card instanceof RewardCard); outputs true 18 9

instanceof operator (2) What is the output? CreditCard joe = new RewardCard(123456, Joe Smith ); CreditCard sue = new CreditCard(234567, Sue Jones ); IO.println(joe instanceof RewardCard); IO.println(sue instanceof RewardCard); IO.println(joe instanceof CreditCard); IO.println(sue instanceof CreditCard); Answer: true false true true 19 import type.lang.*; import type.lib.*; instanceof operator (3) public class DemoInstanceof public static void main(string[] args) // ----------------------- // check for correct usage // ----------------------- if (args.length!= 1) IO.println("-------------------------------------------"); IO.println("Usage: java DemoInstanceof file\n"); IO.println("where 'file' is a credit card database file"); IO.println("(see 'creditcards2.txt' for example file)"); IO.println("-------------------------------------------"); System.exit(0); } // ----------------- // load the database // ----------------- IO.print("Loading the database... "); GlobalCredit gc = new GlobalCredit(); UniReader ur = new UniReader(args[0]); DemoInstanceof.java Demo 20 10

Manual Casts A reference of type sub can be promoted to type super without a cast: RewardCard rc = new RewardCard(123456, John Smith ); CreditCard cc = rc; A RewardCard is a CreditCard However, a reference of type super requires a cast to be demoted to type sub: CreditCard cc = new RewardCard(123456, John Smith ); RewardCard rc = (RewardCard)cc; A CreditCard is not necessarily a RewardCard, therefore a cast is necessary to demote cc 21 Manual Cast Gotchas Object casting (previous slide) affects only the compiler, not the actual object in memory This is different from casting among primitive types where casting a double to an int transforms the stored value While the cast may be allowed at compile time, the VM will generate a run-time error rate if the object is not of the type specified by the cast (avoided by using the instanceof operator before casting) 22 11

Reference Resolution and Binding Promotion allows a reference to point to either the superclass or the subclass If a feature (field, method) is used with the reference, is it the superclass or subclass feature that is used? Determining which requires reference resolution Two possibilities Early binding determined at compile-time (p. 250) Late binding determined at runtime (p. 251) 23 Early and Late Binding Early binding: Correct choices are made at compile time, re the appropriate fields and methods to use with card. Late binding: At runtime, the appropriate charge method is used, as per the reference type of card. This is an example of polymorphic behaviour. 24 12

Reference Resolution 25 Abstract Classes An abstract class is a class that is not fully implemented All the methods are defined, but some are not implemented. Abstract classes cannot be instantiated; however, there may be a service available to get an instance of an abstract class. An example is the Toolkit class in the java.awt package (next slide) 26 13

import type.lang.*; import java.awt.*; Abstract Classes (2) public class DemoToolkit public static void main(string[] args) // Toolkit is an 'abstract' class, so it cannot // be instantiated. That's too bad, because there // are some useful methods available in // Tooklit (see API). One of the methods, // 'getdefaulttooklit', is static and it returns // an instance of Toolkit. This is possible because // the implementation is provided with the Java SDK, // and it 'knows about' the target system. // Let's get it an instance of Toolkit. Toolkit t = Toolkit.getDefaultToolkit(); // Now that we have an instance of Toolkit, we can // do a variety of system-dependent things. Let's // see what the size of the screen is on the // target system. Dimension d = t.getscreensize(); // Print the screen size. IO.println(d); } } DemoToolkit.java Demo 27 Abstract Classes (3) Another example is the Calendar class in the java.util package (see API) GregorianCalendar, implements the methods in Calendar, as appropriate for parts of the world that use Gregorian calendars (see API) GregorianCalendar is defined to extends Calendar ; I.e., it is a subclass of Calendar and it implements the abstract methods in Calendar. GregorianCalendar can be instantiated, even though Calendar cannot (see next slide) 28 14

import type.lang.*; import java.util.*; Abstract Classes (4) public class DemoCalendar public static void main(string[] args) // GregorianCalendar 'extends' the abstract // class Calendar; i.e., it implements the // abstract methods in Calendar (and adds // a few of its own). Get an instance.. Calendar c = new GregorianCalendar(); } } //...and do something with it. Date d = c.gettime(); IO.println(d); DemoCalendar.java Demo 29 Interfaces An interface is similar to an abstract class The main difference is that an abstract class is realized by a subclass that extends the abstract class, whereas an interface is realized by any class that implements the interface An class can implement many interfaces, but a class can be a subclass to only one class An example is the Shape interface, and the Rectangle class that implements Shape (see API) 30 15

import type.lang.*; import java.awt.*; Interfaces (2) public class DemoRectangle public static void main(string[] args) IO.println("Input rectangle position (x,y coordinate of top-left corner):"); IO.print("x: "); int x = IO.readInt(); IO.print("y: "); int y = IO.readInt(); IO.println("\nInput rectangle size (width and height):"); IO.print("width: "); int w = IO.readInt(); IO.print("height: "); int h = IO.readInt(); Rectangle r = new Rectangle(x, y, w, h); while (true) IO.println("\nGive me a test point (or -1 to quit):"); IO.print("x: "); int testx = IO.readInt(); if (testx == -1) DemoRectangle.java Demo 31 Disparate Hierarchies Not in Java! 32 16

Object class 33 Object Class Methods Class getclass() boolean equals(object other) String to String() See API 34 17

Thank You 35 18