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

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

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

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

Object-Oriented Programming More Inheritance

Object-Oriented ProgrammingInheritance & Polymorphism

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

Class Foo. instance variables. instance methods. Class FooTester. main {

Inf1-OP. Creating Classes. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein. February 26, School of Informatics

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

Inheritance and Polymorphism

Inheritance & Polymorphism. Object-Oriented Programming

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

Software Development (cs2500)

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

Java Object Oriented Design. CSC207 Fall 2014

Inheritance & Polymorphism

ITI Introduction to Computing II

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

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

MORE OO FUNDAMENTALS CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 4 09/01/2011

Java Session. Day 2. Reference: Head First Java

What is Inheritance?

ITI Introduction to Computing II

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

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

More OO Fundamentals. CSCI 4448/5448: Object-Oriented Analysis & Design Lecture 4 09/11/2012

First IS-A Relationship: Inheritance

Practice for Chapter 11

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

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

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

Main Topics. Study Tactics. Exam Structure, Roughly. Java Fundamentals. CISC 3120 Midterm Review Guide

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

CS-202 Introduction to Object Oriented Programming

Java Magistère BFA

More Relationships Between Classes

Java Fundamentals (II)

Programming Using C# QUEEN S UNIVERSITY BELFAST. Practical Week 7

Chapter 5 Object-Oriented Programming

Create a Java project named week10

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

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

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

Data Structures (list, dictionary, tuples, sets, strings)

Programming II (CS300)

Inheritance, Polymorphism, and Interfaces

Lecture 4: Extending Classes. Concept

Inf1-OOP. OOP Exam Review. Perdita Stevens, adapting earlier version by Ewan Klein. March 16, School of Informatics

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

Inf1-OP. Inf1-OP Exam Review. Timothy Hospedales, adapting earlier version by Perdita Stevens and Ewan Klein. March 20, School of Informatics

Distributed Systems Recitation 1. Tamim Jabban

CS 251 Intermediate Programming Inheritance

Rules and syntax for inheritance. The boring stuff

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

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

Inheritance (continued) Inheritance

Software and Programming 1

OOP in Java Review. CS356 Object-Oriented Design and Programming October 1, 2014

After a lecture on cosmology and the structure of the solar system, William James was accosted by a little old lady.

COMP 250 Fall inheritance Nov. 17, 2017

COE318 Lecture Notes Week 8 (Oct 24, 2011)

Chapter 14 Abstract Classes and Interfaces

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

Inheritance, polymorphism, interfaces

BBM 102 Introduction to Programming II Spring Inheritance

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

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

Subclass Gist Example: Chess Super Keyword Shadowing Overriding Why? L10 - Polymorphism and Abstract Classes The Four Principles of Object Oriented

Outline. 15. Inheritance. Programming in Java. Computer Science Dept Va Tech August D Barnette, B Keller & P Schoenhoff

Inheritance (Outsource: )

C08: Inheritance and Polymorphism

Inheritance and Interfaces

Class Hierarchy and Interfaces. David Greenstein Monta Vista High School

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University

Object Oriented Programming. Java-Lecture 11 Polymorphism

Object Oriented Features. Inheritance. Inheritance. CS257 Computer Science I Kevin Sahr, PhD. Lecture 10: Inheritance

Inf1-OOP. Data Types. Defining Data Types in Java. type value set operations. Overview. Circle Class. Creating Data Types 1.

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

AP CS Unit 6: Inheritance Notes

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017

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

OLLSCOIL NA heireann THE NATIONAL UNIVERSITY OF IRELAND, CORK. COLAISTE NA hollscoile, CORCAIGH UNIVERSITY COLLEGE, CORK

Methods Common to all Classes

Java: introduction to object-oriented features

Instance Members and Static Members

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

Example: Count of Points

SSE3052: Embedded Systems Practice

COMP 110/L Lecture 19. Kyle Dewey

Object Orientated Programming Details COMP360

Inheritance. Transitivity

CH. 2 OBJECT-ORIENTED PROGRAMMING

CS 251 Intermediate Programming Methods and Classes

Making New instances of Classes

CS 251 Intermediate Programming Methods and More

BCS THE CHARTERED INSTITUTE FOR IT. BCS HIGHER EDUCATION QUALIFICATIONS BCS Level 5 Diploma in IT OBJECT ORIENTED PROGRAMMING

COE318 Lecture Notes Week 9 (Week of Oct 29, 2012)

Inheritance (Part 5) Odds and ends

Week 11: Class Design

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

Transcription:

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

Encapsulation Again Inheritance Encapsulation and Inheritance The Object Superclass Flat vs. Nested Hierarchies Flat Hierarchy Layered Hierarchy Polymorphism Overriding and Overloading Abstract Classes Constructor Chaining Summary/Admin

Encapsulation

Getters and Setters Encapsulation: instance variables should be private public class Student { private String firstname; private String lastname; private String matric; public Student(String fn, String ln, String m) { firstname = fn; lastname = ln; matric = m;

Getters and Setters Encapsulation: instance variables should be private public class StudentTester { public static void main(string[] args) { Student student = new Student("Fiona", "McCleod", "s01234567"); System.out.println(student.firstName); student.matric = "s13141516"; we cannot assign to this variable! we cannot read this variable!

Getters and Setters Encapsulation: instance variables should be private We use instance methods to mediate access to the data in private instance variables. Accessor methods: just read the data Mutator methods: modify the data Java convention: given an instance variable mydata, use getmydata() method to read the data, and setmydata() method to write to the data. Often called getters and setters respectively.

Getters and Setters public class Student { private String firstname, lastname, matric, tutgroup; public Student(String fn, String ln, String m) {... public String getfirstname() { return firstname; public String getlastname() { return lastname; public String getmatric() { return matric;

Getters and Setters Eclipse will generate setters and getters for you!

Inheritance

UML Class Diagrams UML: language for specifying and visualizing OOP software systems UML class diagram: specifies class name, instance variables, methods,... class name - = private + = public UGStudent -matricno -name -age -mailbox +takeexam() +graduate() +party() instance variables instance methods

Classes with Stuff in Common UGStudent -matricno -name -age -mailbox +takeexam() +graduate() +party() PGStudent -matricno -name -age -mailbox +takeexam() +graduate() +party() +tutor() Lots of duplication across the two classes How do we eliminate it?

Classes with Stuff in Common UGStudent -matricno -name -age -mailbox +takeexam() +graduate() +party() PGStudent -matricno -name -age -mailbox +takeexam() +graduate() +party() +tutor() Lots of duplication across the two classes How do we eliminate it?

Abstracting Common Stuff Inheritance hierarchy: subclasses (UG, PG) inherit from superclass (Student) arrow with open head indicates generalization in UML class diagram see http://en.wikipedia.org/wiki/class_diagram Student -matricno -name -age -mailbox +takeexam() +graduate() +party() UGStudent PGStudent +tutor()

Subclasses and superclasses Subclass (e.g. UG) inherits the members of superclass (e.g. Student) Subclass is a specialization of superclass superclass is generalization of subclass [details to be further specified...]

X IS-A Y? The IS-A test Is ClassX a subclass of ClassY? Test: can we say that ClassX IS-A ( is a kind of ) ClassY? Does an instance of ClassX have all the properties (and maybe more) that an instance of ClassY has? IS-A Candidates 1. Kitchen subclass-of Room 2. Room subclass-of House 3. Violinist subclass-of Musician 4. Sink subclass-of Kitchen 5. Musician subclass-of Person 6. Lady Gaga subclass-of Singer 7. Student subclass-of Musician

Inheritance Subclass inherits all the members (instance variables and methods) of the superclass. In Java: subclass extends superclass. A subclass can add new members of its own By default, methods that are inherited from superclass have same implementation in subclass

Inheritance Subclass inherits all the public members (instance variables and methods) of the superclass. In Java: subclass extends superclass. A subclass can add new members of its own By default, methods that are inherited from superclass have same implementation in subclass

Inheritance Subclass inherits all the public members (instance variables and methods) of the superclass. In Java: subclass extends superclass. A subclass can add new members of its own By default, methods that are inherited from superclass have same implementation in subclass except if... subclass overrides the inherited methods.

Doctor Example, 1 Doctor +treatpatient(): void generalization overriding method Surgeon +treatpatient(): void +makeincisions(): void FamilyDoctor +giveadvice(): void For handy guide to UML, see http://www.loufranco.com/blog/assets/cheatsheet.pdf

Doctor Example, 2 Doctor public class Doctor { public void treatpatient() { // perform a checkup

Doctor Example, 3 Surgeon public class Surgeon extends Doctor { public void treatpatient() { // perform surgery // overrides inherited method public void makeincisions() { // use a scalpel // a new method NB We put this class into a new file Surgeon.java

Doctor Example, 4 FamilyDoctor public class FamilyDoctor extends Doctor { public void giveadvice() { // tells you to wrap up warmly // overrides inherited method

Method Overriding Method m in subclass B overrides method m in superclass A if m has exactly the same signature (i.e. name and parameters) and return type as m. In effect, m replaces the implementation of m. Doctor Doctor d = new Doctor(); d.treatpatient(); // Use implementation in Doctor class Surgeon Surgeon s = new Surgeon(); s.treatpatient(); // Use implementation in Surgeon class

Type Hierarchy View in Eclipse Hierarchy Tree Pane Members Pane

Doctor Subclasses Right-click on a class name and select Open Type Hierarchy

FamilyDoctor Members Inherited and non-inherited members

The Design Process 1. Look for objects that have common attributes and behaviours. 2. Design a class that represents the common state and behaviour. 3. Decide if a subclass needs method implementations that are specific to that particular subclass type. 4. Carry out further abstraction by looking for groups of subclasses that might have common behaviours.

Encapsulation and Inheritance Student public class Student { private final String firstname; private final String lastname; private final String matric; public Student(String fn, String ln, String m) {... public String getfirstname() {... public String getlastname() {... public String getmatric() {...

Encapsulation and Inheritance UG public class UG extends Student { private String tutgroup = ""; public void settutgroup(string s) { tutgroup = s; public String gettutgroup() { return tutgroup; public String tostring() { return "UG [firstname=" + firstname + ", lastname=" + lastname + ", matric=" + matric + ", tutgroup=" + tutgroup + "]";

Encapsulation and Inheritance UG public class UG extends Student { private String tutgroup = "";... public String tostring() { return "UG [firstname=" + firstname + ", lastname=" + lastname + ", matric=" + matric + ", tutgroup=" + tutgroup + "]"; Won t work!

Encapsulation and Inheritance UG public class UG extends Student { private String tutgroup = "";... public String tostring() return "UG [firstname=" + getfirstname() + ", " + " lastname=" + getlastname() + ", matric=" + getmatric() + ", tutgroup=" + tutgroup + "]";

Encapsulation and Inheritance private instance variables (fields) cannot be directly accessed by subclass. Can only be accessed via setter and getter methods (which are inherited from superclass).

The Object Superclass

Doctor Example in Eclipse Where does Doctor belong in the class hierarchy?

The class Object Doctor s Superclass public class Doctor { void treatpatient() {...

The class Object Doctor s Superclass public class Doctor extends Object { void treatpatient() {... Object is the superclass of every class in Java! If a class doesn t explicitly extend some superclass, then it implicitly extends Object. That is, we don t need to add extends Object.

Some Methods of Object Object defines methods that are available to every class. E.g., equals(object o) test whether two objects are equal. hashcode() numerical ID; equal objects must have equal hash codes. tostring() returns a textual representation of an object; automatically invoked by methods like System.out.println(). Since every class inherits tostring() from Object, you have already been overriding this method!

Flat vs. Nested Hierarchies

Flat Animal Hierarchy Animal sleep() makenoise() roam() Lion Wolf makenoise() Cat makenoise() Dog makenoise() makenoise()

Animals Example, 1 Our base class: Animal Animal public class Animal { public void sleep() { System.out.println("Sleeping: Zzzzz"); public void makenoise() { System.out.println("Noises..."); public void roam() { System.out.println("Roamin on the plain.");

Animals Example, 2 1. Lion subclass-of Animal 2. Override the makenoise() method. Lion public class Lion extends Animal { public void makenoise() { System.out.println("Roaring: Rrrrrr!");

Animals Example, 3 1. Cat subclass-of Animal 2. Override the makenoise() method. Cat public class Cat extends Animal { public void makenoise() { System.out.println("Miaowing: Miaooo!");

Animals Example, 4 1. Wolf subclass-of Animal 2. Override the makenoise() method. Wolf public class Wolf extends Animal { public void makenoise() { System.out.println("Howling: Ouooooo!");

Animals Example, 5 1. Dog subclass-of Animal 2. Override the makenoise() method. Dog public class Dog extends Animal { public void makenoise() { System.out.println("Barking: Woof Woof!");

Animals Example, 6 The Launcher public class AnimalLauncher { public static void main(string[] args) { System.out.println("\nWolf\n====="); Wolf wolfie = new Wolf(); wolfie.makenoise() ; // from Wolf wolfie.roam(); // from Animal wolfie.sleep(); // from Animal System.out.println("\nLion\n====="); Lion leo = new Lion(); leo.makenoise(); // from Lion leo.roam(); // from Animal leo.sleep(); // from Animal

Animals Example, 7 Output Wolf ===== Howling: Ouooooo! Roamin on the plain. Sleeping: Zzzzz Lion ===== Roaring: Rrrrrr! Roamin on the plain. Sleeping: Zzzzz

Nested Animal Hierarchy Lions and cats can be grouped together into Felines, with common roam() behaviours. Dogs and wolves can be grouped together into Canines, with common roam() behaviours.

Nested Animal Hierarchy Animal sleep() makenoise() roam() Feline roam() Canine roam() Lion makenoise() Cat makenoise() Wolf makenoise() Dog makenoise()

Animals Example, 1 Same as before. Animal public class Animal { public void sleep() { System.out.println("Sleeping: Zzzzz"); public void makenoise() { System.out.println("Noises..."); public void roam() { System.out.println("Roamin on the plain.");

Animals Example, 2 The new class Feline Feline public class Feline extends Animal { public void roam() { // Override roam() System.out.println("Roaming: I m roaming alone.");

Animals Example, 3 The new class Canine Canine public class Canine extends Animal { public void roam() { // Override roam() System.out.println("Roaming: I m with my pack.");

Animals Example, 4 1. Lion subclass-of Feline 2. Override the makenoise() method. Lion public class Lion extends Feline { public void makenoise() { System.out.println("Roaring: Rrrrrr!"); Similarly for Cat.

Animals Example, 5 1. Wolf subclass-of Canine 2. Override the makenoise() method. Wolf public class Wolf extends Canine { public void makenoise() { System.out.println("Howling: Ouooooo!"); Similarly for Dog.

Which method gets called? Animal sleep() makenoise() roam() 1. Wolf wolfie = new Wolf(); 2. wolfie.makenoise(); 3. wolfie.roam(); Canine roam() 4. wolfie.sleep(); Wolf makenoise()

Animals Example, 6 The Launcher public class AnimalLauncher { public static void main(string[] args) { System.out.println("\nWolf\n====="); Wolf wolfie = new Wolf(); wolfie.makenoise(); // from Wolf wolfie.roam(); // from Canine wolfie.sleep(); // from Animal System.out.println("\nLion\n====="); Lion leo = new Lion(); leo.makenoise(); // from Lion leo.roam(); // from Feline leo.sleep(); // from Animal

Animals Example, 7 Output Wolf ===== Howling: Ouooooo! Roaming: I m with my pack. Sleeping: Zzzzz Lion ===== Roaring: Rrrrrr! Roaming: I m roaming alone. Sleeping: Zzzzz

Polymorphism

Typing and Polymorphism polymorphism (= many shapes ): the same piece of code can be assigned multiple types. A class defines a type, namely the signatures of its methods. S is a subtype of T, written S <: T, if a value of type S can be used in any context where a value of type T is expected. The relation <: is reflexive: T <: T The relation <: is transitive: if S <: T and T <: U, then S <: U. NB: We say T is a supertype of S if S is a subtype of T. Inclusion polymorphism: objects of different types S1, S2,... may be treated uniformly as instances of a common supertype T.

Declaring and Initializing a Reference Variable create a Wolf object Wolf wolfie = new Wolf();

Declaring and Initializing a Reference Variable declare a reference variable Wolf wolfie = new Wolf();

Declaring and Initializing a Reference Variable link the object to the reference Wolf wolfie = new Wolf();

Declaring and Initializing a Reference Variable supertype object of subtype Animal wolfie = new Wolf(); Reference type can be supertype of the object type. E.g., Wolf <: Animal.

Polymorphic ArrayList The Launcher public class AnimalLauncher2 { public static void main(string[] args) { Wolf wolfie = new Wolf(); Lion leo = new Lion(); Cat felix = new Cat(); Dog rover = new Dog(); ArrayList< Animal > animals = new ArrayList<Animal>(); animals.add(wolfie); animals.add(leo); animals.add(felix); animals.add(rover); for ( Animal a : animals) { a.makenoise();

Polymorphic Arrays ArrayList<Animal> is polymorphic. animals.add(wolfie) add an object of type Wolf. OK since Wolf <: Animal. for (Animal a : animals) for each object a of type T such that T <: Animal... a.makenoise() if a is of type T, use T s makenoise() method.

Overriding and Overloading

Method Overriding, 1 If a class C overrides a method m of superclass D, then: Parameter lists must be same and return type must be compatible: 1. signature of m in C must be same as signature of m in D; i.e. same name, same parameter list, and 2. return type S of m in C must such that S <: T, where T is return type of m in D. m must be at least as accessible in C as m is in D

private void makenoise() {... Method Overriding, 2 method in Animal public void makenoise() {... Wrong: method in Wolf public void makenoise( int volume ) {... Wrong: method in Wolf

Method Overloading, 1 Overloading: two methods with same name but different parameter lists. Overloaded makenoise public void makenoise() {... public void makenoise(int volume) {... Overloaded println System.out.println(3); // int System.out.println(3.0); // double System.out.println((float) 3.0); // cast to float System.out.println("3.0"); // String

Method Overloading, 2 1. Return types can be different. 2. You can t just change the return type gets treated as an invalid override. 3. Access levels can be varied up or down. Incorrect override of makenoise public String makenoise() { String howl = "Ouooooo!"; return howl; Exception in thread "main" java.lang.error: Unresolved compilation problem: The return type is incompatible with Animal.makeNoise()

Abstract Classes

Animal Objects? Creating new objects Wolf wolfie = new Wolf(); Animal leo = new Lion(); Animal weird = new Animal(); Animal class is meant to contain information that all animals have in common. But this is not enough to define any one specific animal.

Concrete vs. Abstract Concrete Examples: Cat, Wolf Specific enough to be instantiated. Abstract Examples: Animal, Feline Not intended to have instances. Only useful if extended. Any instances will have to be instances of a subclass of the abstract class.

The Abstract Animal, 1 Animal public abstract class Animal { public void sleep() { System.out.println("Sleeping: Zzzzz"); public void makenoise() { System.out.println("Noises..."); public void roam() { System.out.println("Roamin on the plain."); Just put the keyword abstract before the class declaration.

The Abstract Animal, 2 An abstract class can be extended by other abstract classes. Canine and Feline can (and should) both be abstract. Animal public abstract class Animal { public void sleep() { System.out.println("Sleeping: Zzzzz"); public void makenoise() { System.out.println("Noises..."); public void roam() { System.out.println("Roamin on the plain."); Just put the keyword abstract before the class declaration.

The Abstract Animal, 2 Animal public abstract class Animal { public void sleep() { System.out.println(""Sleeping: Zzzzz""); public abstract void roam(); public abstract void makenoise(); Now has abstract methods!

The Abstract Animal, 3 roam() and makenoise() are abstract methods: no body; must be implemented in any concrete subclass (implemented overriden); don t have to be implemented by an abstract subclass; can only be declared in an abstract class; sleep() is not abstract, so can be straightforwardly inherited.

Abstract Classes in Animal Hierarchy <<Abstract>> Animal sleep() makenoise() roam() <<Abstract>> roam() Feline <<Abstract>> roam() Canine Lion makenoise() Cat makenoise() Wolf makenoise() Dog makenoise()

Using Abstract Classes Use an abstract class when you have several similar classes that: have a lot in common the implemented parts of the abstract class have some differences the abstract methods.

Constructor Chaining, 1 All constructors in object s inheritance tree run when a new instance is created. FamilyDoctor extends Doctor Object Doctor FamilyDoctor

Constructor Chaining, 2 Make a new FamilyDoctor(). Call the no-argument superclass constructor, i.e. Doctor(). Call the no-argument superclass constructor, i.e. Object(). Constructor of the immediate superclass invoked with super() If you don t explicitly call this, the compiler will.

Constructor Chaining, 3 Student... public Student(String fn, String ln, String m) { firstname = fn; lastname = ln; matric = m;... UG extends Student... private String tutgroup... public UG(String fn, String ln, String m, String tutgroup) { super(fn, ln, m); // call the superclass constructor this.tutgroup = tutgroup;

Summary Inheriting from a superclass: the subclass gets all the public members (instance variables and methods) of the superclass; public class Foo extends Baz the subclass may add members, and also override methods. So subclass extends (adds to) the behaviour of its superclass. Inheritance corresponds roughly to taxonomic relations for everyday concepts. In Java, you can only inherit from one superclass. Problems with using inheritance: Easy to get muddled with inheritance hierarchies. Subclass is tightly coupled with superclass. Changes in superclass can break subclass fragile base class problem.

Reading Sedgewick & Wayne Section 3.1 (pp. 434 437) Eck http://math.hws.edu/javanotes/c5/index.html or Cay Horstmann (2008) Java Concepts, Chapter 9