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

Similar documents
ITI Introduction to Computing II

ITI Introduction to Computing II

Advanced Placement Computer Science. Inheritance and Polymorphism

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

CS-202 Introduction to Object Oriented Programming

C12a: The Object Superclass and Selected Methods

Programming Languages and Techniques (CIS120)

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

Lecture Notes Chapter #9_b Inheritance & Polymorphism

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

INHERITANCE. Spring 2019

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

Inheritance. The Java Platform Class Hierarchy

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

What is Inheritance?

Inheritance and Polymorphism

Inheritance. 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

Inheritance (continued) Inheritance

Inheritance and Polymorphism

Inheritance. Transitivity

OBJECT ORIENTED PROGRAMMING. Course 4 Loredana STANCIU Room B616

Methods Common to all Classes

CMSC 132: Object-Oriented Programming II

CH. 2 OBJECT-ORIENTED PROGRAMMING

Practice for Chapter 11

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

Inheritance Motivation

Programming Languages and Techniques (CIS120)

Computer Science 210: Data Structures

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

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

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

Chapter 6: Inheritance

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber

CS 112 Programming 2. Lecture 06. Inheritance & Polymorphism (1) Chapter 11 Inheritance and Polymorphism

Chapter 5 Object-Oriented Programming

Programming Languages and Techniques (CIS120)

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

Chapter 10 Classes Continued. Fundamentals of Java

OBJECT ORİENTATİON ENCAPSULATİON

Java Fundamentals (II)

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

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

CSE 8B Programming Assignments Spring Programming: You will have 5 files all should be located in a dir. named PA3:

The Liskov Substitution Principle

PowerPoint Slides. Object-Oriented Design Using JAVA. Chapter 2. by Dale Skrien

M301: Software Systems & their Development. Unit 4: Inheritance, Composition and Polymorphism

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

(SE Tutorials: Learning the Java Language Trail : Interfaces & Inheritance Lesson )

PROGRAMMING LANGUAGE 2

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

Java Magistère BFA

Programming 2. Inheritance & Polymorphism

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

25. Generic Programming

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

CMSC 132: Object-Oriented Programming II

CLASS DESIGN. Objectives MODULE 4

Example: Count of Points

1 Shyam sir JAVA Notes

Inheritance (Deitel chapter 9)

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

Inheritance -- Introduction

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

Object-oriented Programming. Object-oriented Programming

Inheritance & Polymorphism Recap. Inheritance & Polymorphism 1

Class definition. complete definition. public public class abstract no instance can be created final class cannot be extended

Chapter 11 Inheritance and Polymorphism

Introduction to Inheritance

Abstract Class. Lecture 21. Based on Slides of Dr. Norazah Yusof

For this section, we will implement a class with only non-static features, that represents a rectangle

Inheritance (Part 5) Odds and ends

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

Java: introduction to object-oriented features

Programming Languages and Techniques (CIS120)

Inheritance Considered Harmful

Abstract Classes and Interfaces

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

CS1150 Principles of Computer Science Objects and Classes

Programming II (CS300)

First IS-A Relationship: Inheritance

CISC370: Inheritance

Object Oriented Programming. Java-Lecture 11 Polymorphism

Reusing Classes. Hendrik Speleers

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

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

Extending Classes (contd.) (Chapter 15) Questions:

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

ITI Introduction to Computing II

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

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

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

UCLA PIC 20A Java Programming

The Sun s Java Certification and its Possible Role in the Joint Teaching Material

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

Exercise: Singleton 1

Java for Programmers Course (equivalent to SL 275) 36 Contact Hours

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

Transcription:

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

OOP Principles Encapsulation Methods and data are combined in classes Not unique to OOP Information Hiding Implementation of a class can be changed without affecting clients Not unique to OOP (Ada / Modula provided information inheritance) Inheritance Classes can be adapted through inheritance Polymorphism Invocation based on the dynamic type of a reference Substitution rule: Subtypes must fulfill the contract of its base type 2

Inheritance Inheritance in Java New classes can be defined by extending existing classes The extension inherits all fields and methods from the base class New fields, methods and constructors may be added Example Figure Contains position (x, y) Provides method move(dx, dy), getx(), gety() Circle Additional field: radius Additional method: getradius() Rectangle Additional fields: width / height Additional method: getarea() 3

Inheritance in Java Figure class Figure { private int x, y; public int getx() { return x; public int gety() { return y; public void move(int dx, int dy) { x += dx; y += dy; Circle Rectangle class Circle extends Figure { private int radius; class Rectangle extends Figure { private int width, height; public int getradius(){ return radius; public int getarea() { return width * height; 4

Inheritance in Java Extension Class Rectangle inherits the fields x and y Class Rectangle declares new fields width and height Class Rectangle inherits the method move(int dx, int dy) Class Rectangle declares the new method getarea() Rectangle r = new Rectangle(); r.x = 5; r.y = 5; r.width = 20; r.height = 10; r.move(10, 5); r.getarea(); r int x = 515 int y = 510 int width = 20 int height = 10 5

Inheritance in Java Extension Keyword extends class D extends B { Fields and methods are inherited, i.e. are available in the extension and can be accessed / invoked Only one base class can be specified to inherit from; if no base class is specified class Object is the base class Object Animal Figure Mammal Rectangle Circle 6

Inheritance in General Code Inheritance (Extension, Subclassing) Figure has fields x/y and method move Rectangle inherits x/y/move and adds additional fields and methods Figure.Attributes Rectangle.Attributes Interface Inheritance (Specialization, Subtyping) Every rectangle is a figure, but not every figure is a rectangle, i.e. interface specification is reused (and specialized) Type defines a set of objects: Figures Rectangles Implementation Aspect Design Aspect 7

Inheritance in General Code Inheritance (Extension, Subclassing) Subclasses add new fields & methods Subclasses have more (specialized) attributes & operations Circle Figure Implementation Aspect Rectangle Interface Inheritance (Specialization, Subtyping) Types define a set of objects Subtypes are specializations Figure Design Aspect Circle Rectangle 8

Interface Inheritance (Subtyping) Type Type defines a set of values and a set of permissible operations Type only defines a behavior, but no implementation Types are used in declarations of reference variables e.g. Figure f; Java: Types are defined by classes. Subtyping Types can be specialized Subtype defines a is-a relationship The operations defined for a type can also be applied for a subtype Java: Subtyping is defined by subclassing, i.e. each subclass also defines a subtype (i.e. no private inheritance!!!) 9

Method Overriding Method Overriding If in an extension class a method is declared with the same signature as in the base class, then the method in the base class is overridden Overriding # overloading!!! if signatures differ, method in base class is NOT overridden but overloaded! Overriding method hides overridden method Hidden method can be called with a supercall super.<methodname>(arguments) @Override An overriding method can (should) be marked with the @Override annotation 10

Method Overriding Inherited methods may be overridden class Rectangle extends Figure { private int w, h; @Override public void draw() { drawrectangle(x, y, w, h); class TextBox extends Rectangle { private String text; @Override public void draw() { super.draw(); drawstring(x+5, y+5, text); 11

Inheritance: Initialization Initialization of base class What happens when new instance of an extended class is created? Base class and extended class have to be initialized Base class is initialized before extended class is initialized (because extended class may depend on fields in the base class) Constructor of extended class first calls default constructor of base class What happens if such a constructor is not available? Explicit invocation of a constructor in the base class with super( ) a constructor in the base class can be explicitly called super( ) is only allowed as first statement in a constructor a corresponding constructor must be provided by the base class super( ) and this( ) exclude each other 12

Inheritance: Initialization Example class Figure { private int x, y; public Figure(int x, int y) { this.x = x; this.y = y; public void move(int dx, int dy) { x += dx; y += dy; public void draw() { class Rectangle extends Figure { private int w, h; public Rectangle(int x, int y, int w, int h) { super(x, y); this.w = w; this.h = h; public Rectangle(int w, int h) { this(0, 0, w, h); public int getarea() { return w*h; public int getwidth() { return w; public void draw() { /* draw Rectangle */ 13

Inheritance: Initialization Implicit Initialization of Base Class If neither a this( ) nor a super( ) call is declared in a constructor, then the default constructor (no arguments) of the base class is called. if the default constructor does not exist: error! Default Constructor (revisited) class A { => class A { A() { super(); 14

Inheritance in Java: Base Class Object Object (java.lang.object) Direct or indirect base class of all classes (single rooted class tree) Methods String tostring() returns a string representation of the object boolean equals(object obj) returns whether obj is "equal to" this one int hashcode() returns a hash code value for the object void finalize() called by the GC (last wish) Object clone() returns a copy of this Class<?> getclass() returns the runtime class of an object. Synchronization primitives void notify() void notifyall() void wait() void wait(long timeout) void wait(long timeout, int nanos) 15

Inheritance in Java: Base Class Object Default implementations public String tostring() { return getclass().getname() + "@" + Integer.toHexString(hashCode()); public boolean equals(object obj) { return this == obj; All other methods are declared as native (implemented by the JVM) If you want to have another behavior, then override the methods String tostring() boolean equals(object obj) int hashcode() void finalize() Object clone() // same signature!!!! 16

Polymorphism Polymorphic Assignment Instances of extension classes can be assigned to variables of base type Figure f = new Rectangle(0, 0, 4, 2); Static type of f: Figure Static type = type of variable Static type of a variable never changes Dynamic type of f: Rectangle Dynamic type = type of referenced object Dynamic type of a variable may change with every assignment Dynamic Type Static Type 17

Polymorphism Polymorphic Dispatch Dynamic type defines which method is called Figure f = new Rectangle(0, 0, 4, 2); f.draw(); // => Rectangle s draw is called f = new Circle(5, 5, 10); f.draw(); // => Circle s draw is called Figure[] figs = new Figure[]{ new Rectangle(0,0,4,2), new Circle(5,5,10) ; for(int i=0; i < figs.length; i++) { figs[i].draw(); Polymorphism: Definition Polymorphism allows operations to be performed on objects without needing to know which class the object belongs to, provided that we can guarantee that the class implements the specified type 18

Polymorphism Static Type In Java polymorphism is controlled by type declarations Figure f; When a variable is declared as being of a particular type, then we have a language-enforced guarantee that any object referenced by that variable will have (at least) all the features of that type. f.move(2, 3); f.draw(); // works (as expected) Static type defines whether a method call is possible method has to be defined in type declaration static type is responsible for method overload resolution! Dynamic Type Dynamic type is the type of the referenced instance Dynamic type defines which method is executed (dynamic dispatch) 19

Polymorphism Type test: instanceof with the instanceof operator the dynamic type can be inspected if( f instanceof Rectangle)... // returns true if dynamic type of f is // Rectangle (or an extension thereof) // null instanceof C => false Type casts: C-style casts (Rectangle) f // changes the static type of expression f // to Rectangle; // a run-time error is thrown if the // dynamic type of f is not a Rectangle // (or an extension thereof) this type cast allows to access the methods / attributes defined for Rectangle only (and not for Figure). 20

Polymorphism Figure f = new Rectangle(); Rectangle r = (Rectangle) f; f r Rectangle x y w h 21

Polymorphism Liskov Substitution Principle If S is a subtype of T, then objects of type T may be replaced with objects of type S without altering the correctness of the program Whenever you work with an instance of type T, you should not be surprised if you effectively work with an instance of type S An instance of type S can be used at all places where an instance of type T is expected Consequences Overriding methods need to satisfy the rules specified by the base class Overriding methods may do more and expect less 22

Discussion: Which is Subtype of What Square class Square { private int x, y, w; public void setwidth(int w) { this.w = w; public int getwidth() { return w; Rectangle class Rectangle { private int x, y, w, h; public void setwidth(int w) { this.w = w; public void setheight(int h) { this.h = h; public int getwidth() { return w; public int getheight() { return h; 23

Outline Inheritance Abstract Classes Interfaces 24

Figure Example class Figure { int x, y; void draw( ) { class Rectangle extends Figure { int w, h; @Override void draw( ) { /* draw Rectangle at (x,y) */ Text class TextBox extends Rectangle { String text; @Override void draw( ) { Screen.drawText(x, y, text); super.draw(); How to implement draw in Figure? Do we need draw at all here? 25

Abstract Methods Abstract methods only define a signature public abstract void draw( ); have no body have to be implemented in subclasses Abstract methods are useful for polymorphic calls They define the methods which must be provided by subclasses Abstract methods can only be declared in abstract classes 26

Abstract Classes Abstract classes are declared with the abstract keyword public abstract class Figure { private int x, y; public abstract void draw( ); Abstract classes cannot be instantiated, but may have attributes, and thus may have constructors Classes which extend abstract classes have to override (implement) all abstract methods or have to be declared as abstract if not all abstract methods are overridden 27

Figure Example Abstract classes may have attributes Abstract classes may have constructors public abstract class Figure { private int x, y; public Figure(int x, int y) { this.x = x; this.y = y; public int getx() { return x; public int gety() { return y; public void move(int dx, int dy) { x += dx; y += dy; public abstract void draw( ); Abstract classes may have nonabstract methods public class Square extends Figure { private int size; public Square(int x, int y, int w){ super(x,y); size = w; public int getsize() { return size; @Override public void draw( ) { drawrectangle(getx(), gety(), w, w); 28

Abstract Classes: Remarks Abstract Classes and Methods An abstract method must be declared in an abstract class An abstract class must not necessarily contain an abstract method! Useful to declare classes that cannot be instantiated (but extended) Figure[ ] figures = new Figures[10] Arrays of an abstract base type may be instantiated since NO instances are created figures-array can be filled with references to concrete figures figures[0] = new Square(0, 0, 10); figures[1] = new Rectangle(10, 10, 20, 10); for(figure f : figures) { f.draw( ); 29

Abstract Classes: Remarks Abstract Methods can always be called The concrete instances implement these methods Interesting case: calling abstract methods within an abstract class abstract class OutputStream { public abstract void write(byte b); // implementation depends on stream type, i.e. // SocketStream, FileStream, etc. public void write(byte[] buf){ for(int i=0; i<buf.length; i++) write(buf[i]); 30

Abstract Classes: Remarks private Private methods cannot be declared abstract, as private methods cannot be overridden. static Static methods cannot be declared abstract, as static methods can never be overridden. 31

Outline Inheritance Abstract Classes Interfaces 32

Interfaces Characteristics No implementation All methods are by default public and abstract No state All attributes are by default public, static and final (i.e. constants) No constructors Example public interface Figure { int getx(); int gety(); void move(int dx, int dy); void draw(); 33

Interfaces (since Java 8) Default methods Since Java8 interfaces may contain default methods Default methods can access other methods Allows to extend interfaces without breaking existing classes Example public interface Figure { int getx(); int gety(); void move(int dx, int dy); void draw(); default void moveto(int x, int y) { move(x - getx(), y - gety()); 34

Implementation of Interfaces implements Interfaces are implemented in classes All methods defined in the declared interfaces have to be implemented or the class has to be declared abstract class Rectangle implements Figure { private int x, y, w, h; public Rectangle(int x, int y, int w, int h) { this.x = x; this.y = y; this.w = w; this.h = h; @Override public void draw( ) { drawrectangle(x,y,w,h); @Override public void move(int dx, int dy) { x+=dx; y+=dy; @Override public int getx() { return x; @Override public int gety() { return y; public int getwidth() { return w; public int getheight() { return h; 35

Interface and Abstract Base Class Abstract Figure may be used as base class for concrete Figures public abstract class AbstractFigure implements Figure { private int x, y; public AbstractFigure(int x, int y) { this.x=x; this.y=y; @Override public int getx() { return x; @Override public int gety() { return y; @Override public void move(int dx, int dy) { x+=dx; y+=dy; Concrete Figures extend abstract base class public class Rectangle extends AbstractFigure { private int w, h; public Rectangle(int x, int y, int w, int h) { super(x, y); this.w=w; this.h=h; @Override public void draw( ) { drawrectangle(x, y, w, h); 36

Interface and Abstract Base Class Interface: provides a type Abstract class: semi finished component Contains default implementations which can be used in subclasses which can be overridden in subclasses Concrete class: complete component 37

Implementing Multiple Interfaces A class can extend only one class (implicitly class Object) A class can implement several interfaces Example: Polygon provides polygon-specific methods interface Polygon { boolean isconvex(); Rectangle could implement both interfaces Figure (implemented directly or inherited over AbstractFigure) Polygon class Rectangle implements extends AbstractFigure Figure, Polygon implements { Polygon { @Override public void draw( ) {. @Override public boolean isconvex() { 38

Interface Extension Interfaces may be extended all methods of the base interface are inherited additional methods can be specified interface Polygon { boolean isconvex(); interface Polygon2 extends Polygon { Line[] getlines() Interfaces may extend multiple interfaces (multiple subtyping) methods with same name / argument list must have the same return type interface PolygonFigure extends Figure, Polygon {... 39

Interface Variables Interface type can be used to declare reference variables similar to (abstract) classes: reference refers to a class which implements the interface only the methods declared in the interface are available instanceof can be used to check the dynamic type Examples Variable Dynamic Type Static Type Figure f; // interface type f = new Rectangle(0, 0, 300, 200); f.move(30, 30); Parameter void addfigure(figure f) // can be called with any class implementing interface Figure 40

Interface Variables Examples public interface Figure { int getx(); int gety(); void move(int dx, int dy); public interface Polygon { boolean isconvex(); public class Rectangle implements Figure, Polygon { 41

Interface Variables Examples Rectangle r = new Rectangle(0, 0, 50, 30); Figure f = r; // Rectangle implements Figure Polygon p = r; // and Polygon interfaces f.move(20, 20); f.isconvex(); f instanceof Polygon ((Polygon)f).isConvex(); // works // does not work // returns true as the refe- // renced object implements // the interface Polygon // works as the referenced // Object implements the // interface Polygon 42

Interfaces vs. Abstract Classes Abstract Class Abstract class defines a type can be used in declarations Abstract methods only define signature / behavior have to be implemented in extending class abstract class cannot be instantiated Abstract class may contain attributes method implementations A class may extend only one abstract class Interface Interface defines a type can be used in declarations Methods in interface definition only define signature / behavior have to implemented in an implementing class interface cannot be instantiated Interface = pure abstract class no attributes no code A class may implement several interfaces 43

Why Interfaces? Allows to define Interfaces (collection of Methods) independent of a type hierarchy interface Size { int getwidth(); int gethight(); this interface might be implemented by Figures and Cars without the need to extend Figures and Cars from a common subclass (=> unnatural) Size Vehicle Size Figure Car Figure Car 44

Marker Interfaces Definition Interface without methods and constants (=> empty interface) Can be used to add an attribute to a class (jdk1.5: Attributes) Example: java.util.randomaccess Definition package java.util; interface RandomAccess { Declaration class ArrayList implements RandomAccess { // ArrayList declares to support random access Test with instanceof Operator if (list instanceof RandomAccess) { 45

Summary Subclassing = Implementation Inheritance Code inheritance Implementation aspect Subtyping = Interface Inheritance Java Inheritance of behavioral specification Design aspect Class defines type and implementation if the type of a variable is a class name, then the variable may reference an object of the named class or any subclasss of that class Interface defines type if the type of a variable is defined by an interface name, then the variable may reference an object of any class which implements that interface 46