Inheritance. OOP: Inheritance 1

Similar documents
Inheritance. Finally, the final keyword. A widely example using inheritance. OOP: Inheritance 1

Inheritance and Interfaces

Inheritance and Polymorphism

Object-Oriented Languages and Object-Oriented Design. Ghezzi&Jazayeri: OO Languages 1

Java Object Oriented Design. CSC207 Fall 2014

Data Abstraction. Hwansoo Han

Introduction to Object-Oriented Programming

Reusing Classes. Hendrik Speleers

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.

ITI Introduction to Computing II

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

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

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

ITI Introduction to Computing II

Chapter 10 Classes Continued. Fundamentals of Java

Polymorphism. Object Orientated Programming in Java. Benjamin Kenwright

Object Oriented Programming. Java-Lecture 11 Polymorphism

Lecture Notes on Programming Languages

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

Lecture 18 CSE11 Fall 2013 Inheritance

Arrays Classes & Methods, Inheritance

Lecture 13: Object orientation. Object oriented programming. Introduction. Object oriented programming. OO and ADT:s. Introduction

CS111: PROGRAMMING LANGUAGE II

Making New instances of Classes

Inheritance (Deitel chapter 9)

Object Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia

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

CS250 Intro to CS II. Spring CS250 - Intro to CS II 1

More Relationships Between Classes

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

CSE 452: Programming Languages. Previous Lecture. From ADTs to OOP. Data Abstraction and Object-Orientation

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

Instance Members and Static Members

G Programming Languages - Fall 2012

CS 11 java track: lecture 3

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

Chapter 6 Introduction to Defining Classes

What is Inheritance?

Inheritance and Polymorphism

IT101. Inheritance, Encapsulation, Polymorphism and Constructors

Java Fundamentals (II)

CMSC 132: Object-Oriented Programming II

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

Inheritance and Interfaces

Programming II (CS300)

1.00 Lecture 14. Exercise: Plants

Inheritance & Polymorphism Recap. Inheritance & Polymorphism 1

CMSC 132: Object-Oriented Programming II

Computer Programming Inheritance 10 th Lecture

Exercise: Singleton 1

Type Hierarchy. Comp-303 : Programming Techniques Lecture 9. Alexandre Denault Computer Science McGill University Winter 2004

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

Introduction to Computation and Problem Solving

CS 251 Intermediate Programming Inheritance

CS111: PROGRAMMING LANGUAGE II

BBM 102 Introduction to Programming II Spring Abstract Classes and Interfaces

More About Classes CS 1025 Computer Science Fundamentals I Stephen M. Watt University of Western Ontario

Java Class Design. Eugeny Berkunsky, Computer Science dept., National University of Shipbuilding

First IS-A Relationship: Inheritance

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

CH. 2 OBJECT-ORIENTED PROGRAMMING

CS558 Programming Languages Winter 2013 Lecture 8

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

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

Inheritance and Substitution (Budd chapter 8, 10)

Java Basics. Object Orientated Programming in Java. Benjamin Kenwright

Programming Languages and Techniques (CIS120)

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

Software Design and Analysis for Engineers

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

CISC 3115 Modern Programming Techniques Spring 2018 Section TY3 Exam 2 Solutions

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

Inheritance, polymorphism, interfaces

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

COMP 110/L Lecture 19. Kyle Dewey

ECE 3574: Dynamic Polymorphism using Inheritance

Example: Count of Points

Chapter 11. Categories of languages that support OOP: 1. OOP support is added to an existing language

More on Inheritance. Interfaces & Abstract Classes

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

BBM 102 Introduction to Programming II Spring 2017

Inheritance Motivation

Introduction to C++ Introduction to C++ Dr Alex Martin 2013 Slide 1

Inheritance -- Introduction

Inheritance, Polymorphism, and Interfaces

CS313D: ADVANCED PROGRAMMING LANGUAGE

OBJECT ORİENTATİON ENCAPSULATİON

JAVA: A Primer. By: Amrita Rajagopal

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

Programming II (CS300)

8. Polymorphism and Inheritance

IBS Software Services Technical Interview Questions. Q1. What is the difference between declaration and definition?

Inheritance. OOP components. Another Example. Is a Vs Has a. Virtual Destructor rule. Virtual Functions 4/13/2017

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

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

Inheritance. Transitivity

Lecture 5: Inheritance

Programming Languages and Techniques (CIS120)

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

Transcription:

Inheritance Reuse Extension and intension Class specialization and class extension Inheritance The protected keyword revisited Inheritance and methods Method redefinition An widely used inheritance example the composite design pattern Finally, the final keyword OOP: Inheritance 1

How to Reuse Code? Write the class completely from scratch (one extreme). What some programmers always want to do! Find an existing class that exactly match your requirements (another extreme). The easiest for the programmer! Built it from well-tested, well-documented existing classes. A very typical reuse, called composition reuse! Reuse an existing class with inheritance Requires more knowledge than composition reuse. Today's main topic. OOP: Inheritance 2

Class Specialization In specialization a class is considered an Abstract Data Type (ADT). The ADT is defined as a set of coherent values on which a set of operations are defined. A specialization of a class C1 is a new class C2 where The instances of C2 are a subset of the instances of C1. Operations defined of C1 are also defined on C2. Operations defined on C1 can be redefined in C2. C1 C2 OOP: Inheritance 3

Extension The extension of a specialized class C2 is a subset of the extension of the general class C1. Extension of C1 Extension of C2 is-a Relationship A C2 object is a C1 object (but not vice-versa). There is an is-a relationship between C1 and C2. We will later discuss a has-a relationship OOP: Inheritance 4

Class Specialization, Example Shape draw() resize() Circle draw() resize() Line draw() resize() Rectangle draw() resize() Shape Square draw() resize() Circle Line Rectangle Square Should the extensions be overlapping? OOP: Inheritance 5

Class Extension In class extension a class is considered a module. A module is a syntactical frame where a number of variables and method are defined, found in, e.g., Modula-2 and PL/SQL. Class extension is important in the context of reuse. Class extension makes it possible for several modules to share code, i.e., avoid to have to copy code between modules. A class extension of a class C3 is a new class C4 In C4 new properties (variables and methods) are added. The properties of C3 are also properties of C4. C3 C4 OOP: Inheritance 6

Intension The intension of an extended class C4 is a superset of the intension of C3. Intension of C4 Intension of C3 OOP: Inheritance 7

Inheritance Inheritance is a way to derive a new class from an existing class. Inheritance can be used for Specializing an ADT (i.e., class specialization). Extending an existing class (i.e., class extension). Often both class specialization and class extension takes place when a class inherits from an existing class. OOP: Inheritance 8

Module Based vs. Object Oriented C3 C4 Module based Object oriented C3 C4 Class C4 is created by copying C3. There are C3 and C4 instances. Instance of C4 have all C3 properties. C3 and C4 are totally separated. Maintenance of C3 properties must be done two places Languages, e.g., Ada, Modula2, PL/SQL Class C4 inherits from C3. There are C3 and C4 instances. Instance of C4 have all C3 properties. C3 and C4 are closely related. Maintenance of C3 properties must be done in one place. Languages, C++, C#, Java, Smalltalk OOP: Inheritance 9

Composition vs. Inheritance Car start() drive() Shape draw() resize() Engine Gearbox Doors[4] Circle draw() resize() Line draw() resize() Rectangle draw() resize() Pure Composition X a() b() Pure Inheritance (substitution) Square draw() resize() Class extension Y c() d() e() OOP: Inheritance 10

Inheritance in Java class Subclass extends Superclass { // <class body> Superclass method1() method2() Subclass method1() method3() OOP: Inheritance 11

Inheritance Example public class Vehicle { private String make; private String model; public Vehicle() { make = ""; model = ""; public String tostring() { return "Make: " + make + " Model: " + model; public String getmake(){ return make; public String getmodel() { return model; Vehicle tostring() getmake() getmodel() Car public class Car extends Vehicle { private double price; public Car() { super(); // called implicitly can be left outs price = 0.0; public String tostring() { // method overwrites return "Make: " + getmake() + " Model: " + getmodel() + " Price: " + price; public double getprice(){ return price; getprice() OOP: Inheritance 12

Class Specialization and Class Extension The Car type with respect to extension and intension Class Extension Car is a class extension of Vehicle. The intension of Car is increased with the variable price. Class Specialization Car is a class specialization of Vehicle. The extension of Car is decreased compared to the class Vehicle. OOP: Inheritance 13

Instatianting and Initialization Shape Circle Line Rectangle Square Shape Properties Rectangle Properties Square Properties Square Instance The Square, that inherits from Rectangle, that inherits from Shape is instantiated as a single object, with properties from the three classes Square, Rectangle, and Shape. OOP: Inheritance 14

Inheritance and Constructors Constructors are not inherited. A constructor in a subclass must initialize variables in the class and variables in the superclass. What about private fields in the superclass? It is possible to call the superclass' constructor in a subclass. Default superclass constructor called if exists public class Vehicle{ private String make, model; public Vehicle(String ma, String mo) { make = ma; model = mo; public class Car extends Vehicle{ private double price; public Car() { // System.out.println("Start"); // not allowed super(, ); // must be called price = 0.0; OOP: Inheritance 15

Order of Instantiation and Initialization The storage allocated for the object is initialized to binary zero before anything else happens. Static initialization is first done in the base class then the derived classes. The base-class constructor is called. (all the way up to Object). Member initializers are called in the order of declaration. The body of the derived-class constructor is called. OOP: Inheritance 16

Inheritance and Constructors, cont. class A { public A(){ System.out.println("A()"); // when called from B the B.doStuff() is called dostuff(); public void dostuff(){ System.out.println("A.doStuff()"); class B extends A{ int i = 7; public B(){System.out.println("B()"); public void dostuff(){ System.out.println("B.doStuff() " + i); public class Base{ public static void main(string[] args){ B b = new B(); b.dostuff(); //prints A() B.doStuff() 0 B() B.doStuff() 7 OOP: Inheritance 17

Interface to Subclasses and Clients 2 C3 C4 1 3 1. The properties of C3 that clients can use. 2. The properties of C3 that C4 can use. 3. The properties of C4 that clients can use. 4. The properties of C4 that subclasses of C4 can use. 4 = interface OOP: Inheritance 18

protected, Revisited It must be possible for a subclass to access properties in a superclass. private will not do, it is to restrictive public will not do, it is to generous A protected variable or method in a class can be accessed by subclasses but not by clients. Which is more restrictive protected or package access? Change access modifiers when inheriting Properties can be made more public. Properties cannot be made more private. OOP: Inheritance 19

protected, Revisited public Client protected private Shape Circle Line Rectangle Square OOP: Inheritance 20

protected, Example public class Vehicle1 { protected String make; protected String model; public Vehicle1() { make = ""; model = ""; public String tostring() { return "Make: " + make + " Model: " + model; public String getmake(){ return make; public String getmodel() { return model; public class Car1 extends Vehicle1 { private double price; public Car1() { price = 0.0; public String tostring() { return "Make: " + make + " Model: " + model + " Price: " + price; public double getprice(){ return price; Vehicle tostring() getmake() getmodel() Car getprice() OOP: Inheritance 21

Class Hierarchies in General Class hierarchy: a set of classes related by inheritance. Possibilities with inheritance Cycles in the inheritance hierarchy is not allowed. Inheritance from multiple superclass may be allowed. Inheritance from the same superclass more than once may be allowed. A A A A B B B C B C C D C D Multiple and repeated inheritance is a basic feature of Eiffel. [Meyer pp. 62]. OOP: Inheritance 22

Class Hierarchies in Java Class Object is the root of the inheritance hierarchy in Java. If no superclass is specified a class inherits implicitly from Object. If a superclass is specified explicitly the subclass will inherit Object. Object Shape Circle Line Rectangle Square OOP: Inheritance 23

Method/Variable Redefinition Redefinition: A method/variable in a subclass has the same as a method/variable in the superclass. Redefinition should change the implementation of a method, not its semantics. Redefinition in Java class B inherits from class A if Method: Both versions of the method is available in instances of B. Can be accessed in B via super. Variable: Both versions of the variable is available in instances of B. Can be accessed in B via super. There are no language support in Java that checks that a method redefinition does not change the semantics of the method. In the programming language Eiffel assertions (preand post conditions) and invariants are inherited. [Meyer pp. 228]. OOP: Inheritance 24

Upcasting Treat a subclass as its superclass Vehicle tostring() getmake() getmodel() Car getprice() Upcast // example Car c = new Car(); Vehicle v; v = c; // upcast v.tostring(); // okay v.getmake(); // okay //v.getprice(); // not okay Central feature in object-oriented program (covered in next lecture) Should be obvious that a method/field cannot be made more private in a subclass when redefining method/field. However it can be made more public. OOP: Inheritance 25

The Ikea Component List Problem A part can be just the part itself (a brick). A part can consists of part that can consists of parts and so on. As an example a garden house consists of the following parts Garden house walls door knob window frame glass window floor frame glass Regardless whether it is a simple or composite part we just want to print the list. OOP: Inheritance 26

Design of The Ikea Component List Client use Component print() add() remove() components Single print() List print() add() remove() for all components c c.print() The composite design pattern Used extensively when buidling Java GUIs (AWT/Swing) OOP: Inheritance 27

Implementation of The Ikea Component List public class Component{ public void print(){ System.out.println("Do not call print on me!"); public void add(component c){ System.out.println("Do not call add on me!"); public class Single extends Component{ private String name; public Single(String n){ name = n; public void print(){system.out.println(name); public class List extends Component{ private Component[] comp; private int count;// uses parent class public List(){ comp = new Component[100]; count = 0; public void print(){ for(int i = 0; i <= count - 1; i++){ comp[i].print(); public void add(component c){ comp[count++] = c; OOP: Inheritance 28

Implementation of The Ikea Component List public class ComponentClient{ // Ikea public Component makewindow(){ // helper function Component win = new List(); win.add(new Single("frame")); win.add(new Single("glass")); return win; public Component makedoor(){ // helper function Component door = new List(); door.add(new Single("knob")); door.add(makewindow()); return door; public Component makegardenhouse(){ // helper function Component h = new List(); h.add(makedoor()); h.add(makewindow()); // etc return h; public static void main(string[] args){ ComponentClient c = new ComponentClient(); Component brick = new Single("brick"); Component myhouse = c.makegardenhouse(); brick.print(); myhouse.print(); OOP: Inheritance 29

Evaluation of The Ikea Component List Made List and Single classes look alike when printing from the client's point of view. The main objective! Can make instances of Component class, not the intension Can call dummy add/remove methods on these instances Can call add/remove method of Single objects, not the intension. Fixed length, not the intension. Nice design! OOP: Inheritance 30

Fields The final Keyword Compile time constant (very useful) final static double PI = 3.14 Run-time constant (useful) final int RAND = (int) Math.random * 10 Arguments (not very useful) double foo (final int i) Methods Prevents overwriting in a subclass (use this very carefully) Private methods are implicitly final Final class (use this very carefully) Cannot inherit from the class Many details on the impacts of final, see the book. OOP: Inheritance 31

Reuse Summary Use composition when ever possible more flexible and easier to understand than inheritance. Java supports specialization and extension via inheritance Specialization and extension can be combined. A subclass automatically gets the fields and method from the superclass. They can be redefined in the subclass Java supports single inheritance, all have Object as superclass Designing good reusable classes is (very) hard! while(!gooddesign()){ reiteratethedesign(); OOP: Inheritance 32