Topic 7: Inheritance. Reading: JBD Sections CMPS 12A Winter 2009 UCSC

Similar documents
CIS 110: Introduction to computer programming

What is Inheritance?

Inheritance and Polymorphism

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

CMSC 132: Object-Oriented Programming II. Inheritance

Java Object Oriented Design. CSC207 Fall 2014

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

ECE 122. Engineering Problem Solving with Java

Object Oriented Programming: Based on slides from Skrien Chapter 2

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

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

About 1. Chapter 1: Getting started with oop 2. Remarks 2. Examples 2. Introduction 2. OOP Introduction 2. Intoduction 2. OOP Terminology 3.

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

Programming Exercise 14: Inheritance and Polymorphism

Practice for Chapter 11

8. Polymorphism and Inheritance

COMP 401 Spring 2013 Midterm 2

CS-202 Introduction to Object Oriented Programming

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

Inheritance, Polymorphism, and Interfaces

Week 11: Class Design

Goals for Today. CSE1030 Introduction to Computer Science II. CSE1030 Lecture #9. Review is-a versus has-a. Lecture #9 Inheritance I

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

Abstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes.

Programming in C# Inheritance and Polymorphism

C08: Inheritance and Polymorphism

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

Inheritance. Unit 8. Summary. 8.1 Inheritance. 8.2 Inheritance: example. Inheritance Overriding of methods and polymorphism The class Object

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

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

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

First IS-A Relationship: Inheritance

OVERRIDING. 7/11/2015 Budditha Hettige 82

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

Object Oriented Relationships

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

Classes and Inheritance Extending Classes, Chapter 5.2

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

Islamic University of Gaza Faculty of Engineering Computer Engineering Department

Darrell Bethea June 6, 2011

Example: Count of Points

Inheritance -- Introduction

Inheritance and Polymorphism

Implements vs. Extends When Defining a Class

Week 5-1: ADT Design

STUDENT LESSON A20 Inheritance, Polymorphism, and Abstract Classes

ITI Introduction to Computing II

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

Object Oriented Programming. Java-Lecture 11 Polymorphism

Inheritance (continued) Inheritance

25. Generic Programming

COMP 401 Spring 2013 Midterm 2

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

Inheritance & Polymorphism

Inheritance CSC9Y4. Inheritance

C08: Inheritance and Polymorphism

An example from Zoology

CS 251 Intermediate Programming Methods and Classes

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

CS 251 Intermediate Programming Methods and More

ITI Introduction to Computing II

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

C++ Important Questions with Answers

Inheritance. Chapter 7. Chapter 7 1

Person class. A class can be derived from an existing class by using the form

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

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

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

Chapter 6 Introduction to Defining Classes

Admin. CS 112 Introduction to Programming. Recap: OOP Analysis. Software Design and Reuse. Recap: OOP Analysis. Inheritance

public UndergradStudent(String n, String m, String p) { programme = p; super(n, m);

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

Chapter 5 Object-Oriented Programming

More Relationships Between Classes

CO Java SE 8: Fundamentals

Distributed Systems Recitation 1. Tamim Jabban

Polymorphism and Inheritance

Inheritance and Interfaces

More about inheritance

CS313D: ADVANCED PROGRAMMING LANGUAGE

Chapter 14 Abstract Classes and Interfaces

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

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

CLASSES AND OBJECTS IN JAVA

Homework 2 Implementing the University Application Due: November 7, 2004 (Sunday midnight)

Exam Duration: 2hrs and 30min Software Design

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

Exercise: Singleton 1

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

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

CS1020: DATA STRUCTURES AND ALGORITHMS I

Data Abstraction. Hwansoo Han

Distributed Systems Recitation 1. Tamim Jabban

Java Fundamentals (II)

Inheritance and Interfaces

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

CS313D: ADVANCED PROGRAMMING LANGUAGE

CLASS DESIGN. Objectives MODULE 4

Introduction to Inheritance

Chapter 4 Defining Classes I

Transcription:

Topic 7: Inheritance Reading: JBD Sections 7.1-7.6 1

A Quick Review of Objects and Classes! An object is an abstraction that models some thing or process! Examples of objects:! Students, Teachers, Classes, Majors! Cars, Drivers, Races, Entries! Instruments, Measurements, Standards! Lists, Queues, Stacks! Each object has:! Identity (distinguishes it from all other objects)! State (represented by instance variables)! Behavior (represented by instance methods) 2

Review of Objects and Classes (continued)! A class is a user-defined type! Every object is an instance of a class! A class is like a "template" for creating objects! To create an object, use the new keyword! A class has:! One or more constructors (to initialize new objects)! Static variables! Static methods Properties of the class as a whole. One copy of variables for the whole class. Invoke methods using the class name.! Instance variables ("fields")! Instance methods Represent the state and behavior of an object. Each object has its own copy of these variables. Invoke methods using an object reference. 3

Solving Problems with Objects! If you write a description of your problem, the nouns in the description are probably objects! What do you need to remember about each object?! Define instance variables (fields)! Write a constructor to initialize the fields of a new object! Declare the fields private if you do not want users to manipulate them directly! What can each object "do"?! Write instance methods for these behaviors! Decide which methods are public and which are private! Is there some data or function that belongs to the class as a whole, not to any individual object?! Define static variables and static methods 4

Example of a class declaration class Student { private String name; private String major; private double gpa; private boolean coursescompleted; public Student(String name, String major) { this.name = name; this.major = major; this.gpa = 0.0; this.coursescompleted = false; public String getname() { return name; public String getmajor() { return major; public double getgpa() { return gpa; // more methods go here 5

More methods of the Student class class Student { // variables, constructor, accessors go here public void setgpa(double gpa) { this.gpa = gpa; public void setcoursescompleted() { this.coursescompleted = true; public String tostring() { return "Student " + name; public boolean readytograduate() { if (gpa >= 2.0 && coursescompleted) return true; else return false; 6

Using the Student class Student s1 = new Student("Peter", "Physics"); Student s2 = new Student("Michelle", "Math"); Student[] a = {s1, s2; s2.setgpa(3.5); s2.setcoursescompleted(); for (Student s:a) { if (s.readytograduate()) System.out.println(s + " is ready to graduate."); else System.out.println(s + " is not ready to graduate."); Student Peter is not ready to graduate. Student Michelle is ready to graduate. 7

Inheritance! What if some existing class is pretty close to what you need, but not exactly right?! Example: A graduate student is a student with an extra requirement: she must write a thesis! It's wasteful and redundant to create a whole new class for graduate students! A better approach: create GradStudent as a subclass of Student! A subclass "inherits" all the fields and methods of its superclass, PLUS:! It can add more fields and methods! It can override fields and methods 8

Declaring a subclass class GradStudent extends Student { private String thesistopic; private boolean thesiscompleted; // add some more methods here! GradStudent is a subclass of Student! A class may have more than one subclass (GradStudent, RemoteStudent, PartTimeStudent, etc.)! Student is the superclass of GradStudent! A class can have only one superclass! The "is-a" test:! A GradStudent is a Student 9

Objects in Storage! A instance of a subclass looks just like an instance of its superclass, plus some extra fields Stack Name Value Heap gs1 name major gpa coursescompleted thesistopic thesiscompleted the Student part the GradStudent part 10

A Class Hierarchy! Many subclasses may be created to define a class hierarchy: Person Teacher Student Staff Tenured Teacher Graduate Student! Define each field at the highest level where it applies! An object may be created at any level of the hierarchy 11

Another Example of a Type Hierarchy Animal Mammal Reptile Insect Mouse Rabbit Human Fly Bee! Apply the "is-a" test at every level 12

Another Example of a Type Hierarchy Vehicle Boat Car Airplane Sailboat Motor Boat Gas- Powered Car Electric Car Jet Plane Propeller Plane 13

Advantages of Inheritance! Enables re-use of code! Avoids redundancy! Models relationships found in the real world! Makes programs easily extensible to new cases 14

A subclass needs a constructor! First, the subclass constructor calls the constructor of its superclass! Use the keyword super for this! This initializes the inherited fields! Then the subclass constructor initializes its own fields class GradStudent extends Student { private String thesistopic; private boolean thesiscompleted; public GradStudent(String name, String major, String topic) { super(name, major); this.thesistopic = topic; this.thesiscompleted = false; initialize the Student part initialize the GradStudent part 15

A subclass can add new methods class GradStudent extends Student { private String thesistopic; private boolean thesiscompleted; public GradStudent(String name, String major, String topic) { super(n, m); this.thesistopic = t; this.thesiscompleted = false; void setthesiscompleted() { this.thesiscompleted = true; 16

Overriding Methods! A subclass can override (replace) a method of its superclass! The subclass can still invoke the superclass method by using the keyword super class GradStudent extends Student { private String thesistopic; private boolean thesiscompleted; public String tostring() { return "Grad Student " + this.getname(); public boolean readytograduate() { if (super.readytograduate() && thesiscompleted) return true; else return false; 17

Method Selection! When a method is called, Java automatically invokes the method of the most specific type Student s1 = new Student("Bill", "Politics"); s1.readytograduate(); invokes the method of the Student class GradStudent gs2 = new GradStudent("Hillary", "Law", "Health Care Reform"); gs2.readytograduate(); invokes the method of the GradStudent class 18

Subtype Substitution! Since a GradStudent is a Student, it can be used wherever a Student is expected Student s; GradStudent gs; s = new Student("Bill", "Politics"); gs = new GradStudent("Hillary", "Law", "Reforming Health Care"); s = gs; // OK!... but not vice versa gs = s; // Not OK!! A superclass object cannot be assigned to a subclass variable because it does not have all the required fields 19

Polymorphism (Greek: "Many Forms")! An array (or other collection) can contain objects of various subtypes! For each method call, the most specific applicable method is selected Student s = new Student("Bill", "Politics"); GradStudent gs = new GradStudent("Hillary", "Law", "Reforming Health Care"); Student[] students = {s, gs; for (Student s:students) if (s.readytograduate()) System.out.println(s + " is ready."); else System.out.println(s + " is not ready."); Student Bill is not ready. Grad Student Hillary is not ready. 20

Why is polymorphism important?! It keeps type-specific behavior where it belongs (in the class definition, not in the application)! It makes your code extensible to new cases! Example: Suppose you have a program that computes the tuition for every Student. You don't have to add new cases to this program, as long as every new subtype of Student provides its own tuition() method. 21

Overloading vs. Overriding! "Overloading" is method selection based on the static (compile-time) types of the arguments Book b = new Book("War and Peace"); Drink c = new Drink("Decaf Latte"); int charge = price(b) + price(c);! "Overriding" is method selection based on the dynamic (run-time) type of objects in a class hierarchy Student s = new Student(...); GradStudent gs = new GradStudent(...); Student[] students = {s, gs; for (Student s:students) System.out.println(s.readyToGraduate()); 22

Abstract Classes! An abstract class is a class that declares some method signatures without any bodies! The bodies must be provided by subtypes! Example (from this week's homework): abstract class Shape { abstract double area(); public abstract String tostring();! Every subclass of Shape must provide its own area() and tostring() methods class Circle extends Shape { double area() {... String tostring() {... 23

Interfaces! An interface is a named set of method signatures interface Size { public double height(); public double weight();! A class can declare that it implements an interface (it must provide all the required methods) class Mouse implements Size {... ; class House implements Size {... ; class Blouse implements Size {... ; 24

Interfaces (continued)! You can declare an array (or other collection) of different kinds of objects that all implement a common interface: Mouse m1 = new Mouse(... ); House h1 = new House(... ); Blouse b1 = new Blouse(... ); Size[] things = {m1, h1, b1; for (Size s:things) System.out.println("Weight is " + s.weight()); 25

Multiple Inheritance! Some languages (e.g., C++) allow an class to have multiple superclasses Student Employee TeachingAssistant! Java does not support multiple inheritance! But in Java, a class can implement as many interfaces as it likes 26

What makes a language "object-oriented"?! Abstraction! In Java: Classes and methods! Encapsulation! In Java: Private fields and methods! Inheritance! In Java: Subclasses! Polymorphism! In Java: Dynamic method selection 27