Inheritance: Definition

Similar documents
Intro to Computer Science 2. Inheritance

Introduction to Inheritance

Handout 9 OO Inheritance.

Inheritance (P1 2006/2007)

Inheritance Advanced Programming ICOM 4015 Lecture 11 Reading: Java Concepts Chapter 13

Chapter Goals. Chapter 9 Inheritance. Inheritance Hierarchies. Inheritance Hierarchies. Set of classes can form an inheritance hierarchy

CHAPTER 10 INHERITANCE

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

What is Inheritance?

Super-Classes and sub-classes

COP 3330 Final Exam Review

ITI Introduction to Computing II

Object-oriented basics. Object Class vs object Inheritance Overloading Interface

ITI Introduction to Computing II

STUDENT LESSON A5 Designing and Using Classes

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

JAVA MOCK TEST JAVA MOCK TEST II

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

Java Object Oriented Design. CSC207 Fall 2014

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

1 Shyam sir JAVA Notes

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

Inheritance. Notes Chapter 6 and AJ Chapters 7 and 8

Example: Count of Points

Chapter 10 Inheritance. Big Java by Cay Horstmann Copyright 2009 by John Wiley & Sons. All rights reserved.

Inheritance & Abstract Classes Fall 2018 Margaret Reid-Miller

CS-202 Introduction to Object Oriented Programming

Principles of Software Construction: Objects, Design and Concurrency. Inheritance, type-checking, and method dispatch. toad

Overriding Variables: Shadowing

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

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

COSC This week. Will Learn

CMSC 132: Object-Oriented Programming II

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

Inheritance and Polymorphism

Inheritance and Polymorphism. CS180 Fall 2007

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

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

Inheritance and Subclasses

Inheritance (Part 5) Odds and ends

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

Inheritance. Transitivity

Lab05: Inheritance and polymorphism

Inheritance (Part 2) Notes Chapter 6

Inheritance -- Introduction

Inheritance. A mechanism for specialization A mechanism for reuse. Fundamental to supporting polymorphism

Abstract Classes and Polymorphism CSC 123 Fall 2018 Howard Rosenthal

Principles of Software Construction: Objects, Design, and Concurrency

Class, Variable, Constructor, Object, Method Questions

Arrays Classes & Methods, Inheritance

CS260 Intro to Java & Android 03.Java Language Basics

Instance Members and Static Members

CSE 403: Software Engineering, Spring courses.cs.washington.edu/courses/cse403/15sp/ UML Class Diagrams. Emina Torlak

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

Practice for Chapter 11

Programming Languages and Techniques (CIS120)

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

Basic Object-Oriented Concepts. 5-Oct-17

CS 116 Week 8 Page 1

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

CS 251 Intermediate Programming Inheritance

Day 3. COMP 1006/1406A Summer M. Jason Hinek Carleton University

CIS 110: Introduction to computer programming

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

Example: Count of Points

INHERITANCE. Spring 2019

Rules and syntax for inheritance. The boring stuff

CSCI-1200 Computer Science II Fall 2006 Lecture 23 C++ Inheritance and Polymorphism

Making New instances of Classes

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

Inheritance CSC 123 Fall 2018 Howard Rosenthal

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

CSC Inheritance. Fall 2009

Inheritance (cont.) Inheritance. Hierarchy of Classes. Inheritance (cont.)

C++ Important Questions with Answers

24. Inheritance. Java. Fall 2009 Instructor: Dr. Masoud Yaghini

STUDENT LESSON A20 Inheritance, Polymorphism, and Abstract Classes

Exercise: Singleton 1

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

OVERRIDING. 7/11/2015 Budditha Hettige 82

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

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

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

Assignment 2 - Specifications and Modeling

Programming Languages and Techniques (CIS120)

Objectives. Inheritance. Inheritance is an ability to derive a new class from an existing class. Creating Subclasses from Superclasses

ENCAPSULATION AND POLYMORPHISM

Programming Language Concepts Object-Oriented Programming. Janyl Jumadinova 28 February, 2017

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

CS313D: ADVANCED PROGRAMMING LANGUAGE

G Programming Languages - Fall 2012

Lesson 35..Inheritance

Data Abstraction. Hwansoo Han

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

Check out Polymorphism from SVN. Object & Polymorphism

Warm-up: what does this print?

CS/ENGRD 2110 FALL Lecture 6: Consequence of type, casting; function equals

Course Content. Objectives of Lecture 24 Inheritance. Outline of Lecture 24. Inheritance Hierarchy. The Idea Behind Inheritance

Final Exam CS 251, Intermediate Programming December 10, 2014

Course Content. Objectives of Lecture 24 Inheritance. Outline of Lecture 24. CMPUT 102: Inheritance Dr. Osmar R. Zaïane. University of Alberta 4

Transcription:

Inheritance 1

Inheritance: Definition inheritance: a parent-child relationship between classes allows sharing of the behavior of the parent class into its child classes one of the major benefits of object-oriented programming (OOP) is this code sharing between classes through inheritance child class can add new behavior or override existing behavior from parent 2

Inheritance terms superclass, base class, parent class: terms to describe the parent in the relationship, which shares its functionality subclass, derived class, child class: terms to describe the child in the relationship, which accepts functionality from its parent extend, inherit, derive: become a subclass of another class 3

Inheritance in Java in Java, you specify another class as your parent by using the keyword extends public class CheckingAccount extends BankAccount { the objects of your class will now receive all of the state (fields) and behavior (methods) of the parent class constructors and static methods/fields are not inherited by default, a class's parent is Object Java forces a class to have exactly one parent ("single inheritance") other languages (C++) allow multiple inheritance 4

Inheritance Example class BankAccount { private double mybal; public BankAccount() { mybal = 0; public double getbalance() { return mybal; class CheckingAccount extends BankAccount { private double myinterest; public CheckingAccount(double interest) { public double getinterest() { return myinterest; public void applyinterest() { CheckingAccount objects have mybal and myinterest fields, and getbalance(), getinterest(), and applyinterest() methods 5

Multiple layers of inheritance it is possible to extend a class that itself is a child class; inheritance chains like this can be arbitrarily deep public class TransactionFeeCheckingAccount extends CheckingAccount { private static final double FEE = 2.00; public void chargefee() { withdraw(fee); 6

Inheritance Hierarchies Deeper layered chain of classes, many children extending many layers of parents 7

"Has-a" Relationships "Has-a" relationship: when one object contains another as a field public class BankAccountManager { private List myaccounts; //... a BankAccountManager object "has-a" List inside it, and therefore can use it 8

"Is-a" relationships "Is-a" relationships represent sets of abilities; implemented through interfaces and inheritance public class CheckingAccount extends BankAccount { //... a CheckingAccount object "is-a" BankAccount therefore, it can do anything an BankAccount can do it can be substituted wherever a BankAccount is needed a variable of type BankAccount may refer to a CheckingAccount object 9

Using the account classes CheckingAccount inherits BankAccount's methods CheckingAccount c = new CheckingAccount(0.10); System.out.println(c.getBalance()); c.applyinterest(); a BankAccount variable can refer to a CheckingAccount object BankAccount b2 = new CheckingAccount(0.06); System.out.println(b2.getBalance()); an Object variable can point to either account type Object o = new BankAccount(); Object o2 = new CheckingAccount(0.09); 10

Some code that won't compile CheckingAccount variable can't refer to BankAccount (not every BankAccount "is-a" CheckingAccount) CheckingAccount c = new BankAccount(); cannot call a CheckingAccount method on a variable of type BankAccount (can only use BankAccount behavior) BankAccount b = new CheckingAccount(0.10); b.applyinterest(); cannot use any account behavior on an Object variable Object o = new CheckingAccount(0.06); System.out.println(o.getBalance()); o.applyinterest(); 11

Mixing inheritance, interfaces It is legal for a class to extend a parent and to implement any number of interfaces public class BankAccount { //... public class NumberedAccount extends BankAccount implements Comparable { private int mynumber; public int compareto(object o) { return mynumber - ((BankAccount)o).myNumber; 12

Overriding behavior Child class can replace the behavior of its parent's methods by redefining them you have already done this... where? public class BankAccount { private double mybalance; //... public String tostring() { return getid() + " $" + getbalance(); public class FeeAccount extends BankAccount { private static final double FEE = 2.00; public String tostring() { // overriding return getid() + " $" + getbalance() + " (Fee: $" + FEE + ")"; 13

Overriding behavior example BankAccount b = new BankAccount("Ed", 9.0); FeeAccount f = new FeeAccount("Jen", 9.0); System.out.println(b); System.out.println(f); Output: Ed $9.0 Jen $9.0 (Fee: $2.0) 14

UML class diagrams an industry-standard way to draw pictures of your classes and their relationships to each other classes are boxes that list the fields, methods, and constructors of the type classes that have inheritance relationships, or are tightly related to each other, are connected by arrows 15

Class Diagram: Single Class attributes (fields) are written as accessmodifier name : type where accessmodifier is one of - for private + for public # for protected example: - mysize: int methods are written as accessmodifier name(arg1 : type1, arg2 : type2,...) : returntype omit the : returntype if returntype is void example: + withdraw(amount : double) : boolean 16

Class diagram: inheritance inheritance relationships hierarchies drawn top-down with arrows from child to parent if parent is an interface, write its class name in << >> and draw white dashed arrows if parent is a class, use black arrows 17

Class diagram: associations associational relationships 1. multiplicity (how many) 2. name (what relationship the objects have) 3. navigability (who has relationship with whom) 18

Class diagram: example 19

Access modifiers public: visible to all other classes public class BankAccount private: visible only to the current class, its methods, and every instance (object) of its class a child class cannot refer to its parent's private members! private String myid; protected (this one's new to us): visible to the current class, and all of its child classes protected int mywidth; package (default access; no modifier): visible to all classes in the current "package" (seen later) int myheight; 20

Access modifier problem (pt.1) public class Parent { private int field1; protected int field2; public int field3; private void method1() { public void method2() { protected void setfield1(int value) { field1 = value; 21

Access modifier problem (pt.2) public class Child extends Parent { public int field4; public Child() { // Which are legal? field4 = 0; // field1++; // field2++; // field3++; // method1(); // method2(); // setfield1(field4); // 22

Some code that won't compile public class Point2D { private int x, y; public Point2D(int x, int y) { this.x = x; this.y = y; public class Point3D extends Point2D { private int z; public Point3D(int x, int y, int z) { this.x = x; this.y = y; // can't do this! this.z = z; 23

super keyword used to refer to superclass (parent) of current class can be used to refer to parent class's methods, variables, constructors to call them needed when there is a name conflict with current class useful when overriding and you want to keep the old behavior but add new behavior to it syntax: super(args); // call parent s constructor super.fieldname // access parent s field super.methodname(args); // or method 24

super example public class BankAccount { private double mybalance; public void withdraw(double amount) { mybalance -= amount; public class FeeAccount extends BankAccount { public void withdraw(double amount) { super.withdraw(amount); if (getbalance() < 100.00) withdraw(2.00); // charge $2 fee didn't need to say super.getbalance() because the FeeAccount subclass doesn't override that method (it is unambiguous which version of the method we are talking about) 25

super and constructors if the superclass has a constructor that requires any arguments (not ()), you must put a constructor in the subclass and have it call the superconstructor (call to super-constructor must be the first statement) public class Point2D { private int x, y; public Point2D(int x, int y) { this.x = x; this.y = y; public class Point3D extends Point2D { private int z; public Point3D(int x, int y, int z) { super(x, y); // calls Point2D constructor this.z = z; 26

The instanceof keyword Performs run-time type check on the object referred to by a reference variable Usage: object-reference instanceof type (result is a boolean expression) if type is a class, evaluates to true if the variable refers to an object of type or any subclass of it. if type is an interface, evaluates to true if the variable refers to an object that implements that interface. if object-reference is null, the result is false. Example: Object o = mylist.get(2); if (o instanceof BankAccount) ((BankAccount)o).deposit(10.0); 27

Some instanceof problems Object o = new BankAccount(...); BankAccount c = new CheckingAccount(...); BankAccount n = new NumberedAccount(...); CheckingAccount c2 = null; T/F??? o instanceof Object o instanceof BankAccount o instanceof CheckingAccount c instanceof BankAccount c instanceof CheckingAccount n instanceof CheckingAccount n instanceof Comparable n instanceof NumberedAccount c2 instanceof Object 28