Polymorphism and Interfaces. CGS 3416 Spring 2018

Similar documents
Object Oriented Programming. Java-Lecture 11 Polymorphism

26. Interfaces. Java. Fall 2009 Instructor: Dr. Masoud Yaghini

25. Interfaces. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

Chapter 14 Abstract Classes and Interfaces

INHERITANCE. Spring 2019

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

Java Object Oriented Design. CSC207 Fall 2014

Classes and Inheritance Extending Classes, Chapter 5.2

Chapter 10 Classes Continued. Fundamentals of Java

25. Generic Programming

CS-202 Introduction to Object Oriented Programming

OVERRIDING. 7/11/2015 Budditha Hettige 82

Abstract Classes and Interfaces

Inheritance, Polymorphism, and Interfaces

CS/ENGRD 2110 FALL Lecture 7: Interfaces and Abstract Classes

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

CS111: PROGRAMMING LANGUAGE II

Chapter 5 Object-Oriented Programming

Inheritance and object compatibility

Announcement. Agenda 7/31/2008. Polymorphism, Dynamic Binding and Interface. The class will continue on Tuesday, 12 th August

CS/ENGRD 2110 SPRING Lecture 7: Interfaces and Abstract Classes

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

Programming II (CS300)

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

Java Inheritance. Written by John Bell for CS 342, Spring Based on chapter 6 of Learning Java by Niemeyer & Leuck, and other sources.

Object. OutputStream write(int) write(byte[]) write(byte[], int, int) FilterOutputStream write(int) write(byte[]) write(byte[], int, int)

Lecture 5: Inheritance

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

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

Inheritance & Abstract Classes Fall 2018 Margaret Reid-Miller

First IS-A Relationship: Inheritance

CS 251 Intermediate Programming Inheritance

CS260 Intro to Java & Android 03.Java Language Basics

OBJECT ORİENTATİON ENCAPSULATİON

Polymorphism and Inheritance

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

CST242 Object-Oriented Programming Page 1

Chapter 11 Classes Continued

Inheritance and Polymorphism

Chapter 13 Abstract Classes and Interfaces. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

Lecture Notes Chapter #9_c Abstract Classes & Interfaces

ITI Introduction to Computing II

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

What is Inheritance?

Inheritance and Polymorphism

We are on the GUI fast track path

Abstract Classes and Interfaces

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

ITI Introduction to Computing II

Motivations. Objectives. object cannot be created from abstract class. abstract method in abstract class

IST311. Advanced Issues in OOP: Inheritance and Polymorphism

8. Polymorphism and Inheritance

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

Introduction to Computation and Problem Solving

CS/ENGRD 2110 SPRING 2018

Inheritance and Polymorphism

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

Inheritance & Polymorphism Recap. Inheritance & Polymorphism 1

Inheritance and Polymorphism

Chapter 13 Abstract Classes and Interfaces

Inheritance. Benefits of Java s Inheritance. 1. Reusability of code 2. Code Sharing 3. Consistency in using an interface. Classes

OBJECT ORIENTED PROGRAMMING. Course 4 Loredana STANCIU Room B616

Inheritance. The Java Platform Class Hierarchy

Programming in the Large II: Objects and Classes (Part 2)

ECE 3574: Dynamic Polymorphism using Inheritance

Java Programming Lecture 7

More Relationships Between Classes

CS111: PROGRAMMING LANGUAGE II

PROGRAMMING III OOP. JAVA LANGUAGE COURSE

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber

Inheritance (continued) Inheritance

CMSC 132: Object-Oriented Programming II

Lesson 10. Work with Interfaces and Abstract Classes. Copyright all rights reserved

Object-Oriented Concept

Java How to Program, 8/e

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

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

Inheritance, Polymorphism and the Object Memory Model

Polymorphism 2/12/2018. Which statement is correct about overriding private methods in the super class?

QUIZ. Write the following for the class Bar: Default constructor Constructor Copy-constructor Overloaded assignment oper. Is a destructor needed?

Advanced Placement Computer Science. Inheritance and Polymorphism

Chapter 3 Syntax, Errors, and Debugging. Fundamentals of Java

CH. 2 OBJECT-ORIENTED PROGRAMMING

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

Practice for Chapter 11

Inheritance and Polymorphism. CS180 Fall 2007

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

Abstract Classes and Polymorphism CSC 123 Fall 2018 Howard Rosenthal

Inheritance and Interfaces

Polymorphism. Agenda

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

CMSC 132: Object-Oriented Programming II

Motivations. Chapter 13 Abstract Classes and Interfaces

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

Outline. Subtype Polymorphism, Subtyping vs. Subclassing, Liskov Substitution Principle. Benefits of Subtype Polymorphism. Subtype Polymorphism

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

UNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 11 CLASSES CONTINUED

This week. Tools we will use in making our Data Structure classes: Generic Types Inheritance Abstract Classes and Interfaces

index.pdf January 21,

Need to store a list of shapes, each of which could be a circle, rectangle, or triangle

Transcription:

Polymorphism and Interfaces CGS 3416 Spring 2018

Polymorphism and Dynamic Binding If a piece of code is designed to work with an object of type X, it will also work with an object of a class type that is derived from X (any subclass of X). This is a feature known as polymorphism and is implemented by the Java interpreter through a mechanism called dynamic binding. Suppose there is a base class called Shape. Suppose that Rectangle, Triangle, and Circle are all subclasses of Shape. Then it is legal to attach derived objects to the base reference variables: Shape s1 = new Circle(); Shape s2 = new Rectangle(); Shape s3 = new Triangle();

Polymorphism and Dynamic Binding Suppose a method findarea() is called through one of these variables (s1, s2, s3) in the above example. The method must exist in the Shape class, but there can be override versions in the subclasses. If so, then through dynamic binding, the method that runs will be based on the attached object s type, as a priority over the reference variable type (Shape): s1.findarea(); // from the Circle class s2.findarea(); // from the Rectangle class s3.findarea(); // from the Triangle class If any of these subclasses did not override the finarea() method, then the Shape class findarea() method will run.

Polymorphism and Dynamic Binding If a method expects a parameter of type X, it is legal to pass in an object of a type derived from X in that slot: // Sample method public int draw(shape s) { // definition code } // sample calls Shape s1 = new Shape(); Shape s2 = new Circle(); Shape s3 = new Rectangle(); draw(s1); // normal usage draw(s2); // passing in a Circle object draw(s3); // passing in a Rectangle object

Another Example Notice that a useful application of polymorphism is to store many related items, but with slightly different types (i.e. subclasses of the same superclass), in one storage container for example, an array and then do common operations on them through overridden functions. Assume the setup in the previous example, base class Shape and derived classes Rectangle, Circle, Triangle. Suppose the base class has a findarea() method (probably abstract, since we don t know how to compute the area for a generic shape), and each derived class has its own findarea() method. Note that in the for-loop, the appropriate area methods are called for each shape attached to the array, without the need for separate storage for different shape types (i.e. no need for an array of circles, and a separate array of rectangles, etc).

Another Example Shape[] list = new Shape[size]; // create an array of Shape reference variables list[0] = new Circle(); // attach a Circle to first array slot list[1] = new Rectangle(); // attach a Rectangle to second slot list[2] = new Triangle(); // attach a Triangle to third slot for (int i = 0; i < list.length; i++) System.out.println("The area of shape " + i + " = " + list[i].findarea())

Casting Since a derived object can always be attached to a corresponding base class reference variable, this is a type of casting that is implicitly allowed. Similarly, direct assignment between variables (derived type assigned into base type) in this order is also allowed, as are explicit cast operations. Shape s1, s2; // Shape is the base class Circle c; // Circle is a derived class s1 = new Circle(); // automatically legal s2 = c; // automatically legal s1 = (Shape)c; // explicit cast used, but equivalent to above

Casting To convert an instance of a superclass (base) to an instance of a subclass (derived), the explicit cast operation must be used: c = s1; // would be illegal -- cast needed c = (Circle)s1; // legal (though not always so useful)

The instanceof operator The instanceof operator checks to see if the first operand (a variable) is an instance of the second operand (a class), and returns a response of type boolean. Shape s1; Circle c1; // other code... if (s1 instanceof Circle) c1 = (Circle)s1; // cast to a Circle variable

Interfaces Java does not allow multiple inheritance A subclass can only be derived from one base class with the keyword extends In Java, the interface can obtain a similar effect to multiple inheritance Interface - A construct that contains only constants and abstract methods Similar to abstract class Different, since an abstract class can also contain regular variables and methods Can use as a base type name (just like regular base classes) Cannot instantiate (like an abstract class)

Format for declaring an interface: modifier interface Name { constant declarations abstract method signatures - keyword "abstract" not needed. ALL methods in an interface are abstract } Use the keyword implements to state that a class will use a certain interface. In this example, Comparable is the name of an interface. The class ComparableCircle inherits the data from the Comparable interface, and would then need to implement the methods (to be able to use them). class CompCircle extends Circle implements Comparable { //... }

Other rules: Only single inheritance for classes, with extends Interfaces can inherit other interfaces (even multiple), with extends public interface NewInterface extends interface1,..., interfacen classes can implement more than one interface with implements public class NewClass extends BaseClass implements interface1,..., interfacen

The Cloneable interface A special interface in the Java.lang package which happens to be empty: public interface Cloneable { } This is a marker interface no data or methods, but special meaning in Java. A class can use the clone() method (inherited from class Object) only if it implements Cloneable.