Polymorphism. Polymorphism Abstract Classes Interfaces

Size: px
Start display at page:

Download "Polymorphism. Polymorphism Abstract Classes Interfaces"

Transcription

1 References: Beginning Java Objects, Jacquie Barker; Teach Yourself Object Oriented Programming in 21 Days, Anthony Sintes; Sara Stoecklin, FSU; IT350 Internet lectures 9/25/ Polymorphism Abstract Classes Interfaces 9/25/ Polymorphism Polymorphism is the ability of two or more objects belonging to different classes to respond to the same message in different ways (at run time). If a surgeon, a hairdresser and an actor all hear the message cut! each will respond in a different way. If these three professions were classes, then the cut message would have specific meaning to each class. 9/25/

2 Revisiting the Student/Grad Student Example class Student void print ( System.out.println( name : + \nid : + studentid + \n Major: + major + \ngpa : + gpa); //end print //end Student class GraduateStudent extends Student void print() 1 super.print(); System.out. println( Undergrad Deg: + undergraddegree + \nundergrad Inst: + undergradinstitution + \nthis IS A GRAD STUDENT ); //end print //end GraduateStudent class UndergraduateStudent extends Student void print() super.print(); System.out. Println( High School Attended: + highschool + \nthis IS AN UNDERGRAD STUDENT ); //end print //end UndergraduateStudent 2 1. GraduateStudent defines a print method specific for a grad student after calling on the general print method of Student. 2. UndergraduateStudent defines a print method specific for an undergrad student after calling on the general print method of Student. 9/25/ Revisiting the Student/GradStudent Example public class UseStudentClass Student [] studentbody = new Student[20]; UndergraduateStudentug1 = new UndergraduateStudent(); UndergraduateStudentug2 = new UndergraduateStudent(); GraduateStudent g1 = new GraduateStudent(); GraduateStudent g2 = new GraduateStudent();. //populate the array in random order studentbody]0] = ug1; studentbody]1] = g1; studentbody]2] = ug2; studentbody]3] = g2;. //Print attributes of all students for ( inti=0; i<20; i++) studentbody[i].print(); The array holds references to Student objects which, because of inheritance, can be either UndergraduateStudent or GraduateStudent references. Each object knows which version of the print() method to execute based on its internal knowledge of its type/class //end UseStudentClass 9/25/ Benefit of Polymorphism Without polymorphism, all the printing scenarios for different kinds of students would have to be tested in a series of if statements. for (int i=0; i<20; i++) if(studentbody[i] is an undergrad) printasundergradstudent(); else if(studentbody[i] is a grad student) printasgraduatestudent(); else. Different functions needed to print each kind of student Or, we would need a single print() method with the if test hidden inside. public print() if(this is an undergrad student) print attributes of undergrad student else if(this is a graduate student) print attributes of a graduate student else if. If we later define a MS student or a PhD student, the code body in either case must be modified, becoming more spaghettilike. 9/25/

3 How Does Polymorphism Work? Declaring an object only reserves enough memory to hold a reference to it. The memory to house the object is only allocated when a call to new is executed. Student y; Memory for a reference y = new Student(); This is dynamic instantiation Memory for an object Dynamic instantiation and dynamic binding are necessary for polymorphism and overriding. Static instantiation and compile time binding are what make overloading work. 9/25/ How Does Polymorphism Work? With procedure oriented languages, for any particular function call, the compiler can determine at compile-time what function gets called by matching the call against all of the method signatures that have been declared. This is static (compile time) binding Overloaded methods are checked at compile time With object-oriented languages it may not be possible to determine until runtime which function gets called. 9/25/ How Does Polymorphism Work? Dynamic binding refers to the process of connecting a function call with the appropriate method at runtime. A polymorphic function is one that requires dynamic binding. 9/25/

4 How Does Polymorphism Work? //main application Person p; Student s; Professor pr; if (some runtime condition) p = new Student(); else p = new Professor(); p.print(); It is not known at compile time which object will call the print method. Only at runtime is the object instantiated and the type/class of the object selected. 1 2 class Student extends Person.. public void print(int a, int b) //end print end Student class Professor extends Person.. public void print(int a, int b) //end print end Professor 1. p=new Student() was executed 2. p= new Professor() was executed 9/25/ class Base public void f() System.out.println( Base::f(() ); class Derived extends Base public void f() System.out.println( Derived::f() ); public class Test public static void main (String[] args) //Math.random() returns a random value >= 0.0 and < 1.0 if ( Math.random() > 0.5 ) g (new Derived()); else g (new Base()); public static void g (Base b) b.f(); Polymorphism The output of this code depends on the dynamic type passed to method g(). 9/25/ Polymorphism Polymorphism fulfills the goals of OO by producing software that is Natural: Enables you to more naturally model the real world and to program at the conceptual level of the problem instead of specific implementations. Overloading lets you concentrate on what an object does, not what kinds of parameters it might process Reliable: Results in reliable code because it simplifies code. You can write one case instead of many cases for each type of object you may manipulate. Don t have to update code each time you add a new subclass. You can write less code. 9/25/

5 Polymorphism Polymorphism fulfills the goals of OO by producing software that is Reusable: Maintainable: Extendable: Timely: For reuse, an object only needs to know the second object s interface, not the details of the implementation. Results in less code, so there is less to maintain. Code is less bulky and so, easier to maintain. You can add new subtypes to a system without having to alter the system to use the new subtype. With overloading, you can add new methods without having to worry about name conflicts. If you can write less code, you can deliver it sooner. You can add new types almost instantly to a program. Maintaining and extending is much faster. 9/25/ Static vs Dynamic Types A reference to an object is declared to be a reference to a specific static type. At runtime it may refer to objects of its static type or any object type that inherits from its static type. The dynamic type of an object reference may change. For example: Polygon p = new Rectangle(); The static type of p is Polygon. The dynamic type is Rectangle. 9/25/ class Base public void f(object o) System.out.println("Base::f(Object)"); //end f //end Base class Derived extends Base public void f(string s) System.out.println("Derived::f(String)"); //end f //end Derived public class Test public static void main(string[] args) Base b = new Derived(); b.f("think"); //end main //end Test Base::f(Object) Output Static vs Dynamic Types The static type of b is Base; the dynamic type of b is Derived Since f is not overridden, but overloaded in Derived, the call b.f( Think ) is bound at compile time to the Base method f(object) 9/25/

6 Static vs Dynamic Types Here is a simple, 2-step test you can use to determine which method will execute for any method call: 1. Associate the method call with a declaration statically. But, 2. If the method being called is non-static and is overridden, you consider the dynamic type of the object calling the function to resolve the method call to an actual implementation; otherwise, consider the static type of the object when resolving the method call. 9/25/ Abstract Classes An abstract class specifies the required behaviors of a class without having to provide an explicit implementation of each behavior. i.e., guarantees that subclasses use the base class properly Extended classes provide specific implementation of some or all of the methods. Each method not implemented in an abstract class is specifically marked abstract. Note: if all you need is to define a set of methods that someone will support, but provide no implementation, you should probably use an interface instead. 9/25/ Abstract Classes abstract class Boat protected int size; protected int weight; public abstract void turnright(); public class SailBoat extends Boat private int numberofsails; public void turnright() public void describe() //SailBoat inherits size and weight attributes //from Boat System.out.println( Size: + size); System.out.println( Weight: + weight); System.out.println( Number of sails: + numberofsails); The class Boat is an abstract class because it represents an abstract concept: a floatable conveyance that can turn right. It identifies a behavior without implementing it. Many other kinds of boats could be defined to extend Boat: MotorBoat, Canoe, etc. All would have the same abstract features of a Boat. 9/25/

7 Abstract Classes abstract class Boat protected String name; public abstract void turnright(); public String getidentification(); public class SailBoat extends Boat private int numberofsails; public void turnright() public class MotorBoat extends Boat private int licensenumber; public void turnright(); public String getidentification(); The classes MotorBoat and SailBoat extend the class Boat. Boat is an abstract class because it s impossible to specify the implementation for the method turnright(). The following call is polymorphic: Boat b;//can t do this... b.turnright(); Boat is an abstract class, so b must reference a specific type of boat (i.e. b = new?). It's impossible to determine what b will refer to at compile time, so the call is polymorphic. 9/25/ Abstract Classes Whenever a class contains one or more abstract methods, then the class as a whole is considered to be an abstract class. All methods in an abstract class don t have to be abstract; it can also contain concrete methods -- methods with a signature and a body. Because some of the implementation is missing, you can t create an instance of an abstract class. 9/25/ Abstract Classes in Java Many Java classes use inheritance and polymorphism public abstract class InputStream public abstract int read(); public class StringBufferInputStream extends InputStream protected String buffer; protected int pos; public int read() return buffer.charat(pos++); public class FileInputStream extends InputStream public native int read(); public void consumer(inputstream instream) int i = instream.read (); 9/25/

8 Abstract Classes Abstract classes solve the problem inherent in generalizing two existing classes that each have a method with the same signature, but different logic. class Professor String name; String ssn; float hourlysalary; public float computepay (int hrsworked) return hrsworked * hourlysalary; //end computepay //end Professor Same signature, different logic class Student String name; String ssn; float monthlystipend; int minimumrequiredhrs; public float computepay(int hrsworked) if (hrsworked > minimumrequiredhrs ) return monthlystipend; else return 0.0F; //end computepay //end Student 9/25/ Abstract Classes Solution is to create Person as an abstract class and define computepay() as an abstract method. public abstract class Person String name; String ssn; public abstract float computepay (int hrsworked); class Professor extends Person String name; String ssn; float hourlysalary; public float computepay (int hrsworked) return hrsworked * hourlysalary; //end computepay //end Professor class Student extends Person String name; String ssn; float monthlystipend; int minimumrequiredhrs; public float computepay(int hrsworked) if (hrsworked > minimumrequiredhrs ) return monthlystipend; else return 0.0F; //end computepay //end Student 9/25/ Interfaces 9/25/

9 Interfaces Java allows only single inheritance, not multiple inheritance Person Person Athlete Student Student Java has the mechanism of interfaces to provide some of the functionality of multiple inheritance 9/25/ Java Interfaces The term interface is an overloaded word. It can refer to the public messages you can send to an object or to the Java mechanism for representing abstractions. Java Interfaces are like classes without any implementation. The only value an interface provides is a new type. An interface provides a set of specifications of methods; it does not provide any code for the methods. (They look like class definitions inside C++ header files.) An interface can also provide a set of constants. 9/25/ Basic syntax Interfaces interface name constants method signatures Interface methods may not be static, because static methods are class-specific. All attributes in an interface are implicitly static and final (i.e.constants). 9/25/

10 Interfaces All methods in an interface are essentially abstract, and so no special keyword is required in their signatures. The keyword implements is used to specify that a class will implement an interface. Interfaces cannot be instantiated with new. Each class that implements an interface must implement all of its methods, or, if the class does not implement all of the methods, that class must be declared abstract. 9/25/ public interface Programmable void setcurrenttime (int mo, int d, int h, int m); void setchannel(int c); void setstart(int d, int h, int m); void setstop(int d, int h, int m); // end Programmable Notice how the VCR class has provided implementations for every method defined in the Programmable interface. It has to; otherwise the compiler will complain! Using this technique VCR can extend one class and implement as many as needed. Interface - Example public class VCR implements Programmable private int month, day, hour, minute; private int startday, starthour, startminute; private int stopday, stophour, stopminute; private int channel; public void setcurrenttime(int mo, int d, int h, int m) month=mo; day=d; hour = h; minute=m; // end setcurrenttime public void setchannel(int c) channel = c; // end setchannel public void setstart(int d, int h, int m) startday = d; starthour = h; startminute =m; // end setstart public void setstop(int d, int h, int m) stopday = d; stophour = h; stopminute = m; 9/25/2003 // end setstop 29 // end VCR Java Interfaces - Example public interface Programmable void setcurrenttime (int mo, int d,int h, int m); void setchannel(int c); void setstart(int d, int h, int m); void setstop(int d, int h, int m); // end Programmable public class SmartTV implements Programmable private int month, day, hour, minute; private int startday, starthour, startminute; private int stopday, stophour, stopminute; private int channel; public void setcurrenttime(int mo, int d, int h, int m) // end setcurrenttime public void setchannel(int c) Again, Notice how the channel = c; SmartTV class has provided // end setchannel implementations for every method defined in the public void setstart(int d, int h, int m) Programmable interface, startday = d; starthour = h; startminute =m; although one of the methods // end setstart has no statements. public void setstop(int d, int h, int m) stopday = d; stophour = h; stopminute = m; 9/25/2003 // end setstop 30 // end SmartTv 10

11 Java Interfaces Example 2 //Taxpayer.java public interface TaxPayer public static final int TAXYEAR=2002; public static final double TAXRATE = 0.40; public float filetaxes(); public void displaytaxreturn(int year); //FamousPerson.java public interface FamousPerson public void liststagenames(); public boolean starredin(string film); //Person.java public class Person implements TaxPayer,FamousPerson protected String name; public void setname(string name) this.name = name; public void liststagenames() public boolean starredin(string film) public float filetaxes() public void displaytaxreturn(int year) Java s answer to multiple inheritance 9/25/ Java Interfaces An object can simultaneously have any one of several identities by implementing multiple interfaces. The object can be plugged in to any method where any of its identities is appropriate. For example: class Film public void castactorinfilm (FamousPerson p); Any object belonging to a class that implements the FamousPerson interface can be passed in as an argument to this method, because if an object implements an interface, then it is an object of that type. 9/25/ Interfaces Use an interface to define methods that can extend the functionality of a variety of different classes. Defining a class that implements an interface allows the class to attach the methods contained in the interface. Example: java s ActionListener interface adds actionperformed() -- a method that enables objects to perform actions in response to events (e.g. mouse click) 9/25/

12 ActionListener interface Public abstract ActionListener extends EventListener public abstract void actionperformed(actionevent e); Details of the action performed are left to the implementor 9/25/ Interface Comparable java.lang.comparable: public interface Comparable public int compareto(object o); The Comparable interface is used to capture the abstraction of relative comparison or ordering. For example, people can be compared or ordered by height, weight, grade point average, etc. Stars can be ordered by age, distance from earth, size, etc. The interface captures the abstraction of ordering but doesn't say what defines the order (age, height, weight, etc). 9/25/ Interface Comparable The definition of the interface's only method compareto(object o) determines what defines the ordering. The semantics of compareto(object o) are: when the object that compareto() is called for is less than the parameter o, the result should be negative; if equal the result should be 0; if greater than, the result should be positive. 9/25/

13 Interface Comparable /** * Interface to compare the equality of two objects * */ public interface Comparable /** * Compare this object to a desired object. If current is * larger, then * return 1; if the tocompare object is larger, then return -1. * If the two objects are equal, return 0 tocompare the object for comparison -1 if tocompare > this, 0 if tocompare == this, * 1 if this > tocompare */ public int compareto (Object tocompare); All Comparable objects must implement the compare method. The interface is a contract the implementing class must fulfill. 9/25/ Example usage of Comparable public class Sort public static void sort(comparabledata[]) int n = data.length; for(int i=0;i<n-1;i++) for(int j=n-1; j>i;j--) // Descending sort if (data[j].compareto(data[j-1]) < 0) swap(data,j,j-1); public static void swap(object data[], int a, int b) Object o = data[a]; data[a] = data[b]; data[b] = o; 9/25/ Interface Comparable A reference to a Comparable object can refer to any object that implements the Comparable interface. For example, the numeric wrapper classes such as Integer, Float, etc. all implement the interface Comparable, so the following is valid: Integer i = new Integer(3); Comparable c = i; 9/25/

14 Interfaces Interfaces can extend other interfaces public interface Sortable extends Collectible A class implementing the Sortable interface must also fulfill the contract of the Collectible interface. 9/25/ Interfaces Using Java interfaces is good practice because it separates the definition of the interface from the class implementation of that interface You can write code to abstractions, which facilitates reuse When you separate interface from implementation, many otherwise unrelated classes could implement the interface you could write a routine that sorts objects of any type that implements the abstraction or interface Comparable (e.g. Integer, Float, Student, Telephone) Like inheritance, objects that share a common interface can also take part in substitutability relationships without having to be part of the same inheritance hierarchy. [Sintes,142] 9/25/

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

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University Day 4 COMP1006/1406 Summer 2016 M. Jason Hinek Carleton University today s agenda assignments questions about assignment 2 a quick look back constructors signatures and overloading encapsulation / information

More information

What are the characteristics of Object Oriented programming language?

What are the characteristics of Object Oriented programming language? What are the various elements of OOP? Following are the various elements of OOP:- Class:- A class is a collection of data and the various operations that can be performed on that data. Object- This is

More information

CS 251 Intermediate Programming Inheritance

CS 251 Intermediate Programming Inheritance CS 251 Intermediate Programming Inheritance Brooke Chenoweth University of New Mexico Spring 2018 Inheritance We don t inherit the earth from our parents, We only borrow it from our children. What is inheritance?

More information

Inheritance (continued) Inheritance

Inheritance (continued) Inheritance Objectives Chapter 11 Inheritance and Polymorphism Learn about inheritance Learn about subclasses and superclasses Explore how to override the methods of a superclass Examine how constructors of superclasses

More information

Chapter 5 Object-Oriented Programming

Chapter 5 Object-Oriented Programming Chapter 5 Object-Oriented Programming Develop code that implements tight encapsulation, loose coupling, and high cohesion Develop code that demonstrates the use of polymorphism Develop code that declares

More information

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018 Object-oriented programming 1 and data-structures CS/ENGRD 2110 SUMMER 2018 Lecture 4: OO Principles - Polymorphism http://courses.cs.cornell.edu/cs2110/2018su Lecture 3 Recap 2 Good design principles.

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Inheritance Introduction Generalization/specialization Version of January 20, 2014 Abstract

More information

Inheritance, Polymorphism, and Interfaces

Inheritance, Polymorphism, and Interfaces Inheritance, Polymorphism, and Interfaces Chapter 8 Inheritance Basics (ch.8 idea) Inheritance allows programmer to define a general superclass with certain properties (methods, fields/member variables)

More information

Inheritance and Polymorphism

Inheritance and Polymorphism Inheritance and Polymorphism Recitation 10/(16,17)/2008 CS 180 Department of Computer Science, Purdue University Project 5 Due Wed, Oct. 22 at 10 pm. All questions on the class newsgroup. Make use of lab

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Inheritance Introduction Generalization/specialization Version of January 21, 2013 Abstract

More information

Inheritance and Interfaces

Inheritance and Interfaces Inheritance and Interfaces Object Orientated Programming in Java Benjamin Kenwright Outline Review What is Inheritance? Why we need Inheritance? Syntax, Formatting,.. What is an Interface? Today s Practical

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Inheritance (part II) Polymorphism Version of January 21, 2013 Abstract These lecture notes

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Inheritance (part II) Polymorphism Version of January 21, 2013 Abstract These lecture notes

More information

What is Inheritance?

What is Inheritance? Inheritance 1 Agenda What is and Why Inheritance? How to derive a sub-class? Object class Constructor calling chain super keyword Overriding methods (most important) Hiding methods Hiding fields Type casting

More information

COP 3330 Final Exam Review

COP 3330 Final Exam Review COP 3330 Final Exam Review I. The Basics (Chapters 2, 5, 6) a. comments b. identifiers, reserved words c. white space d. compilers vs. interpreters e. syntax, semantics f. errors i. syntax ii. run-time

More information

Inheritance and Polymorphism

Inheritance and Polymorphism Inheritance and Polymorphism Dr. M. G. Abbas Malik Assistant Professor Faculty of Computing and IT (North Jeddah Branch) King Abdulaziz University, Jeddah, KSA mgmalik@kau.edu.sa www.sanlp.org/malik/cpit305/ap.html

More information

IT101. Inheritance, Encapsulation, Polymorphism and Constructors

IT101. Inheritance, Encapsulation, Polymorphism and Constructors IT101 Inheritance, Encapsulation, Polymorphism and Constructors OOP Advantages and Concepts What are OOP s claims to fame? Better suited for team development Facilitates utilizing and creating reusable

More information

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

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub Lebanese University Faculty of Science Computer Science BS Degree Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub 2 Crash Course in JAVA Classes A Java

More information

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

Topic 7: Inheritance. Reading: JBD Sections CMPS 12A Winter 2009 UCSC 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,

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

index.pdf January 21,

index.pdf January 21, index.pdf January 21, 2013 1 ITI 1121. Introduction to Computing II Circle Let s complete the implementation of the class Circle. Marcel Turcotte School of Electrical Engineering and Computer Science Version

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Interface Abstract data types Version of January 26, 2013 Abstract These lecture notes are meant

More information

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

Abstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes. a and Interfaces Class Shape Hierarchy Consider the following class hierarchy Shape Circle Square Problem AND Requirements Suppose that in order to exploit polymorphism, we specify that 2-D objects must

More information

STUDENT LESSON A20 Inheritance, Polymorphism, and Abstract Classes

STUDENT LESSON A20 Inheritance, Polymorphism, and Abstract Classes STUDENT LESSON A20 Inheritance, Polymorphism, and Abstract Classes Java Curriculum for AP Computer Science, Student Lesson A20 1 STUDENT LESSON A20 Inheritance, Polymorphism, and Abstract Classes INTRODUCTION:

More information

CS-202 Introduction to Object Oriented Programming

CS-202 Introduction to Object Oriented Programming CS-202 Introduction to Object Oriented Programming California State University, Los Angeles Computer Science Department Lecture III Inheritance and Polymorphism Introduction to Inheritance Introduction

More information

Object-Oriented Programming

Object-Oriented Programming References: Beginning Java Objects by Jacquie Barker; Designing Object-Oriented Software by Rebecca Wirfs- Brock;Object-oriented Analysis & Design by Grady Booch; Sara Stoecklin 9/11/2003 1 Object Oriented

More information

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

CSCI-142 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community CSCI-12 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community http://csc.cs.rit.edu 1. Provide a detailed explanation of what the following code does: 1 public boolean checkstring

More information

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

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner. HAS-A Relationship Association is a relationship where all objects have their own lifecycle and there is no owner. For example, teacher student Aggregation is a specialized form of association where all

More information

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

Chapter 11 Inheritance and Polymorphism. Motivations. Suppose you will define classes to model circles, Chapter 11 Inheritance and Polymorphism 1 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common features. What is the best way to design

More information

More Relationships Between Classes

More Relationships Between Classes More Relationships Between Classes Inheritance: passing down states and behaviors from the parents to their children Interfaces: grouping the methods, which belongs to some classes, as an interface to

More information

Object Oriented Programming. Java-Lecture 11 Polymorphism

Object Oriented Programming. Java-Lecture 11 Polymorphism Object Oriented Programming Java-Lecture 11 Polymorphism Abstract Classes and Methods There will be a situation where you want to develop a design of a class which is common to many classes. Abstract class

More information

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber Chapter 10 Inheritance and Polymorphism Dr. Hikmat Jaber 1 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common features. What is the

More information

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and Classes CS 251 Intermediate Programming Methods and Classes Brooke Chenoweth University of New Mexico Fall 2018 Methods An operation that can be performed on an object Has return type and parameters Method with

More information

CS 251 Intermediate Programming Methods and More

CS 251 Intermediate Programming Methods and More CS 251 Intermediate Programming Methods and More Brooke Chenoweth University of New Mexico Spring 2018 Methods An operation that can be performed on an object Has return type and parameters Method with

More information

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

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming Overview of OOP Object Oriented Programming is a programming method that combines: a) Data b) Instructions for processing that data into a self-sufficient object that can be used within a program or in

More information

Object-Oriented Programming. Objects. Objects. Objects

Object-Oriented Programming. Objects. Objects. Objects References: Beginning Java by Jacquie Barker; Designing Object-Oriented Software by Rebecca Wirfs- Brock;Object-oriented Analysis & Design by Grady Booch; Sara Stoecklin Object Oriented Programming defined

More information

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

HAS-A Relationship. If A uses B, then it is an aggregation, stating that B exists independently from A. HAS-A Relationship Association is a weak relationship where all objects have their own lifetime and there is no ownership. For example, teacher student; doctor patient. If A uses B, then it is an aggregation,

More information

First IS-A Relationship: Inheritance

First IS-A Relationship: Inheritance First IS-A Relationship: Inheritance The relationships among Java classes form class hierarchy. We can define new classes by inheriting commonly used states and behaviors from predefined classes. A class

More information

Java: introduction to object-oriented features

Java: introduction to object-oriented features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer Java: introduction to object-oriented features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer

More information

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

CS/ENGRD 2110 SPRING Lecture 7: Interfaces and Abstract Classes CS/ENGRD 2110 SPRING 2019 Lecture 7: Interfaces and Abstract Classes http://courses.cs.cornell.edu/cs2110 1 Announcements 2 A2 is due Thursday night (14 February) Go back to Lecture 6 & discuss method

More information

Chapter 13. Inheritance and Polymorphism. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

Chapter 13. Inheritance and Polymorphism. CS 180 Sunil Prabhakar Department of Computer Science Purdue University Chapter 13 Inheritance and Polymorphism CS 180 Sunil Prabhakar Department of Computer Science Purdue University Introduction Inheritance and polymorphism are key concepts of Object Oriented Programming.

More information

8. Polymorphism and Inheritance

8. Polymorphism and Inheritance 8. Polymorphism and Inheritance Harald Gall, Prof. Dr. Institut für Informatik Universität Zürich http://seal.ifi.uzh.ch/info1 Objectives Describe polymorphism and inheritance in general Define interfaces

More information

Lecture 02, Fall 2018 Friday September 7

Lecture 02, Fall 2018 Friday September 7 Anatomy of a class Oliver W. Layton CS231: Data Structures and Algorithms Lecture 02, Fall 2018 Friday September 7 Follow-up Python is also cross-platform. What s the advantage of Java? It s true: Python

More information

Java Fundamentals (II)

Java Fundamentals (II) Chair of Software Engineering Languages in Depth Series: Java Programming Prof. Dr. Bertrand Meyer Java Fundamentals (II) Marco Piccioni static imports Introduced in 5.0 Imported static members of a class

More information

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

Day 5. COMP1006/1406 Summer M. Jason Hinek Carleton University Day 5 COMP1006/1406 Summer 2016 M. Jason Hinek Carleton University today s agenda assignments Assignment 2 is in Assignment 3 is out a quick look back inheritance and polymorphism interfaces the Comparable

More information

[ L5P1] Object-Oriented Programming: Advanced Concepts

[ L5P1] Object-Oriented Programming: Advanced Concepts [ L5P1] Object-Oriented Programming: Advanced Concepts Polymorphism Polymorphism is an important and useful concept in the object-oriented paradigm. Take the example of writing a payroll application for

More information

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

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring Java Outline Java Models for variables Types and type checking, type safety Interpretation vs. compilation Reasoning about code CSCI 2600 Spring 2017 2 Java Java is a successor to a number of languages,

More information

Chapter 10 Classes Continued. Fundamentals of Java

Chapter 10 Classes Continued. Fundamentals of Java Chapter 10 Classes Continued Objectives Know when it is appropriate to include class (static) variables and methods in a class. Understand the role of Java interfaces in a software system and define an

More information

Lecture 18 CSE11 Fall 2013 Inheritance

Lecture 18 CSE11 Fall 2013 Inheritance Lecture 18 CSE11 Fall 2013 Inheritance What is Inheritance? Inheritance allows a software developer to derive a new class from an existing one write code once, use many times (code reuse) Specialization

More information

Lecture 5: Inheritance

Lecture 5: Inheritance McGill University Computer Science Department COMP 322 : Introduction to C++ Winter 2009 Lecture 5: Inheritance Sami Zhioua March 11 th, 2009 1 Inheritance Inheritance is a form of software reusability

More information

Collections. Collections Collection types Collection wrappers Composite classes revisited Collection classes Hashtables Enumerations

Collections. Collections Collection types Collection wrappers Composite classes revisited Collection classes Hashtables Enumerations References: Beginning Java Objects, Jacquie Barker; The Java Programming Language, Ken Arnold and James Gosling; IT350 Internet lectures 9/16/2003 1 Collections Collection types Collection wrappers Composite

More information

Overview. ITI Introduction to Computing II. Interface 1. Problem 1. Problem 1: Array sorting. Problem 1: Array sorting. Problem 1: Array sorting

Overview. ITI Introduction to Computing II. Interface 1. Problem 1. Problem 1: Array sorting. Problem 1: Array sorting. Problem 1: Array sorting Overview ITI 1121. Introduction to Computing II Rafael Falcon and Marcel Turcotte (with contributions from R. Holte) Electrical Engineering and Computer Science University of Ottawa Interface Abstract

More information

Programming in C# Inheritance and Polymorphism

Programming in C# Inheritance and Polymorphism Programming in C# Inheritance and Polymorphism C# Classes Classes are used to accomplish: Modularity: Scope for global (static) methods Blueprints for generating objects or instances: Per instance data

More information

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

Course Content. Objectives of Lecture 24 Inheritance. Outline of Lecture 24. Inheritance Hierarchy. The Idea Behind Inheritance Structural Programming and Data Structures Winter 2000 CMPUT 102: Dr. Osmar R. Zaïane Course Content Introduction Objects Methods Tracing Programs Object State Sharing resources Selection Repetition Vectors

More information

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

Course Content. Objectives of Lecture 24 Inheritance. Outline of Lecture 24. CMPUT 102: Inheritance Dr. Osmar R. Zaïane. University of Alberta 4 Structural Programming and Data Structures Winter 2000 CMPUT 102: Inheritance Dr. Osmar R. Zaïane Course Content Introduction Objects Methods Tracing Programs Object State Sharing resources Selection Repetition

More information

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

Object Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia Object Oriented Programming in Java Jaanus Pöial, PhD Tallinn, Estonia Motivation for Object Oriented Programming Decrease complexity (use layers of abstraction, interfaces, modularity,...) Reuse existing

More information

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

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner. HAS-A Relationship Association is a relationship where all objects have their own lifecycle and there is no owner. For example, teacher student Aggregation is a specialized form of association where all

More information

CMSC 132: Object-Oriented Programming II. Inheritance

CMSC 132: Object-Oriented Programming II. Inheritance CMSC 132: Object-Oriented Programming II Inheritance 1 Mustang vs Model T Ford Mustang Ford Model T 2 Interior: Mustang vs Model T 3 Frame: Mustang vs Model T Mustang Model T 4 Compaq: old and new Price:

More information

Java Object Oriented Design. CSC207 Fall 2014

Java Object Oriented Design. CSC207 Fall 2014 Java Object Oriented Design CSC207 Fall 2014 Design Problem Design an application where the user can draw different shapes Lines Circles Rectangles Just high level design, don t write any detailed code

More information

Objects and Classes: Working with the State and Behavior of Objects

Objects and Classes: Working with the State and Behavior of Objects Objects and Classes: Working with the State and Behavior of Objects 1 The Core Object-Oriented Programming Concepts CLASS TYPE FACTORY OBJECT DATA IDENTIFIER Classes contain data members types of variables

More information

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

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University Lecture 3 COMP1006/1406 (the Java course) Summer 2014 M. Jason Hinek Carleton University today s agenda assignments 1 (graded) & 2 3 (available now) & 4 (tomorrow) a quick look back primitive data types

More information

Advanced Placement Computer Science. Inheritance and Polymorphism

Advanced Placement Computer Science. Inheritance and Polymorphism Advanced Placement Computer Science Inheritance and Polymorphism What s past is prologue. Don t write it twice write it once and reuse it. Mike Scott The University of Texas at Austin Inheritance, Polymorphism,

More information

Abstract Classes and Interfaces

Abstract Classes and Interfaces Abstract Classes and Interfaces Reading: Reges and Stepp: 9.5 9.6 CSC216: Programming Concepts Sarah Heckman 1 Abstract Classes A Java class that cannot be instantiated, but instead serves as a superclass

More information

Announcements. Final exam. Course evaluations. Saturday Dec 15 10:20 am -- 12:20 pm Room: TBA

Announcements. Final exam. Course evaluations. Saturday Dec 15 10:20 am -- 12:20 pm Room: TBA Announcements Final exam Saturday Dec 15 10:20 am -- 12:20 pm Room: TBA Course evaluations Wednesday November 28th Need volunteer to collect evaluations and deliver them to LWSN. 1 Chapter 13 Inheritance

More information

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

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University CS5000: Foundations of Programming Mingon Kang, PhD Computer Science, Kennesaw State University OOP Three main programming mechanisms that constitute object-oriented programming (OOP) Encapsulation Inheritance

More information

IMACS: AP Computer Science A

IMACS: AP Computer Science A IMACS: AP Computer Science A OVERVIEW This course is a 34-week, 4 classroom hours per week course for students taking the College Board s Advanced Placement Computer Science A exam. It is an online course

More information

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

Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II Mahmoud El-Gayyar elgayyar@ci.suez.edu.eg Ad hoc-polymorphism Outline Method overloading Sub-type Polymorphism Method overriding Dynamic

More information

More about inheritance

More about inheritance Main concepts to be covered More about inheritance Exploring polymorphism method polymorphism static and dynamic type overriding dynamic method lookup protected access 4.1 The inheritance hierarchy Conflicting

More information

Collections Algorithms

Collections Algorithms Collections Algorithms 1 / 11 The Collections Framework A collection is an object that represents a group of objects. The collections framework allows different kinds of collections to be dealt with in

More information

Inheritance and Polymorphism

Inheritance and Polymorphism Object Oriented Programming Designed and Presented by Dr. Ayman Elshenawy Elsefy Dept. of Systems & Computer Eng.. Al-Azhar University Website: eaymanelshenawy.wordpress.com Email : eaymanelshenawy@azhar.edu.eg

More information

Practice for Chapter 11

Practice for Chapter 11 Practice for Chapter 11 MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. 1) Object-oriented programming allows you to derive new classes from existing

More information

OBJECT ORİENTATİON ENCAPSULATİON

OBJECT ORİENTATİON ENCAPSULATİON OBJECT ORİENTATİON Software development can be seen as a modeling activity. The first step in the software development is the modeling of the problem we are trying to solve and building the conceptual

More information

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

Outline. Inheritance. Abstract Classes Interfaces. Class Extension Overriding Methods Inheritance and Constructors Polymorphism. 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

More information

Fundamentals of Object Oriented Programming

Fundamentals of Object Oriented Programming INDIAN INSTITUTE OF TECHNOLOGY ROORKEE Fundamentals of Object Oriented Programming CSN- 103 Dr. R. Balasubramanian Associate Professor Department of Computer Science and Engineering Indian Institute of

More information

Super-Classes and sub-classes

Super-Classes and sub-classes Super-Classes and sub-classes Subclasses. Overriding Methods Subclass Constructors Inheritance Hierarchies Polymorphism Casting 1 Subclasses: Often you want to write a class that is a special case of an

More information

Collections. Collections. Collections - Arrays. Collections - Arrays

Collections. Collections. Collections - Arrays. Collections - Arrays References: Beginning Java Objects, Jacquie Barker; The Java Programming Language, Ken Arnold and James Gosling; IT350 Internet lectures Collections Collection types Collection wrappers Composite classes

More information

Design issues for objectoriented. languages. Objects-only "pure" language vs mixed. Are subclasses subtypes of the superclass?

Design issues for objectoriented. languages. Objects-only pure language vs mixed. Are subclasses subtypes of the superclass? Encapsulation Encapsulation grouping of subprograms and the data they manipulate Information hiding abstract data types type definition is hidden from the user variables of the type can be declared variables

More information

Java for Non Majors Spring 2018

Java for Non Majors Spring 2018 Java for Non Majors Spring 2018 Final Study Guide The test consists of 1. Multiple choice questions - 15 x 2 = 30 points 2. Given code, find the output - 3 x 5 = 15 points 3. Short answer questions - 3

More information

CPS 506 Comparative Programming Languages. Programming Language

CPS 506 Comparative Programming Languages. Programming Language CPS 506 Comparative Programming Languages Object-Oriented Oriented Programming Language Paradigm Introduction Topics Object-Oriented Programming Design Issues for Object-Oriented Oriented Languages Support

More information

CSE115 / CSE503 Introduction to Computer Science I. Dr. Carl Alphonce 343 Davis Hall Office hours:

CSE115 / CSE503 Introduction to Computer Science I. Dr. Carl Alphonce 343 Davis Hall Office hours: CSE115 / CSE503 Introduction to Computer Science I Dr. Carl Alphonce 343 Davis Hall alphonce@buffalo.edu Office hours: Thursday 12:00 PM 2:00 PM Friday 8:30 AM 10:30 AM OR request appointment via e-mail

More information

Introduction to Inheritance

Introduction to Inheritance Introduction to Inheritance James Brucker These slides cover only the basics of inheritance. What is Inheritance? One class incorporates all the attributes and behavior from another class -- it inherits

More information

PROGRAMMING LANGUAGE 2

PROGRAMMING LANGUAGE 2 31/10/2013 Ebtsam Abd elhakam 1 PROGRAMMING LANGUAGE 2 Java lecture (7) Inheritance 31/10/2013 Ebtsam Abd elhakam 2 Inheritance Inheritance is one of the cornerstones of object-oriented programming. It

More information

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

CS 112 Programming 2. Lecture 06. Inheritance & Polymorphism (1) Chapter 11 Inheritance and Polymorphism CS 112 Programming 2 Lecture 06 Inheritance & Polymorphism (1) Chapter 11 Inheritance and Polymorphism rights reserved. 2 Motivation Suppose you want to define classes to model circles, rectangles, and

More information

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

CS/ENGRD 2110 FALL Lecture 7: Interfaces and Abstract Classes CS/ENGRD 2110 FALL 2017 Lecture 7: Interfaces and Abstract Classes http://courses.cs.cornell.edu/cs2110 1 Announcements 2 A2 is due tomorrow night (17 February) Get started on A3 a method every other day.

More information

Inheritance and Interfaces

Inheritance and Interfaces Inheritance and Interfaces what is inheritance? examples & Java API examples inheriting a method overriding a method polymorphism Object tostring interfaces Ex: sorting and Comparable interface Inheritance

More information

Inheritance. Transitivity

Inheritance. Transitivity Inheritance Classes can be organized in a hierarchical structure based on the concept of inheritance Inheritance The property that instances of a sub-class can access both data and behavior associated

More information

Derived and abstract data types. TDT4205 Lecture 15

Derived and abstract data types. TDT4205 Lecture 15 1 Derived and abstract data types TDT4205 Lecture 15 2 Where we were We ve looked at static semantics for primitive types and how it relates to type checking We ve hinted at derived types using a multidimensional

More information

EKT472: Object Oriented Programming. Overloading and Overriding Method

EKT472: Object Oriented Programming. Overloading and Overriding Method EKT472: Object Oriented Programming Overloading and Overriding Method 2 Overriding Versus Overloading Do not confuse overriding a method in a derived class with overloading a method name When a method

More information

COMP1008 An overview of Polymorphism, Types, Interfaces and Generics

COMP1008 An overview of Polymorphism, Types, Interfaces and Generics COMP1008 An overview of Polymorphism, Types, Interfaces and Generics Being Object-Oriented Exploiting the combination of: objects classes encapsulation inheritance dynamic binding polymorphism pluggability

More information

Rules and syntax for inheritance. The boring stuff

Rules and syntax for inheritance. The boring stuff Rules and syntax for inheritance The boring stuff The compiler adds a call to super() Unless you explicitly call the constructor of the superclass, using super(), the compiler will add such a call for

More information

Implements vs. Extends When Defining a Class

Implements vs. Extends When Defining a Class Implements vs. Extends When Defining a Class implements: Keyword followed by the name of an INTERFACE Interfaces only have method PROTOTYPES You CANNOT create on object of an interface type extends: Keyword

More information

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

MORE OO FUNDAMENTALS CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 4 09/01/2011 MORE OO FUNDAMENTALS CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 4 09/01/2011 1 Goals of the Lecture Continue a review of fundamental object-oriented concepts 2 Overview of OO Fundamentals

More information

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

Software Paradigms (Lesson 3) Object-Oriented Paradigm (2) Software Paradigms (Lesson 3) Object-Oriented Paradigm (2) Table of Contents 1 Reusing Classes... 2 1.1 Composition... 2 1.2 Inheritance... 4 1.2.1 Extending Classes... 5 1.2.2 Method Overriding... 7 1.2.3

More information

1.00 Lecture 13. Inheritance

1.00 Lecture 13. Inheritance 1.00 Lecture 13 Inheritance Reading for next time: Big Java: sections 10.5-10.6 Inheritance Inheritance allows you to write new classes based on existing (super or base) classes Inherit super class methods

More information

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

Computer Science II (20073) Week 1: Review and Inheritance Computer Science II 4003-232-01 (20073) Week 1: Review and Inheritance Richard Zanibbi Rochester Institute of Technology Review of CS-I Hardware and Software Hardware Physical devices in a computer system

More information

Inheritance and Substitution (Budd chapter 8, 10)

Inheritance and Substitution (Budd chapter 8, 10) Inheritance and Substitution (Budd chapter 8, 10) 1 2 Plan The meaning of inheritance The syntax used to describe inheritance and overriding The idea of substitution of a child class for a parent The various

More information

Chapter 5. Inheritance

Chapter 5. Inheritance Chapter 5 Inheritance Objectives Know the difference between Inheritance and aggregation Understand how inheritance is done in Java Learn polymorphism through Method Overriding Learn the keywords : super

More information

Inheritance Motivation

Inheritance Motivation Inheritance Inheritance Motivation Inheritance in Java is achieved through extending classes Inheritance enables: Code re-use Grouping similar code Flexibility to customize Inheritance Concepts Many real-life

More information

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

More About Objects. Zheng-Liang Lu Java Programming 255 / 282 More About Objects Inheritance: passing down states and behaviors from the parents to their children. Interfaces: requiring objects for the demanding methods which are exposed to the outside world. Polymorphism

More information

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

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs. Local Variable Initialization Unlike instance vars, local vars must be initialized before they can be used. Eg. void mymethod() { int foo = 42; int bar; bar = bar + 1; //compile error bar = 99; bar = bar

More information