Polymorphism.

Slides:



Advertisements
Similar presentations
Written by: Dr. JJ Shepherd
Advertisements

Subclasses. Inheritance class Animal { int row, column; // will be inherited private Model model; // private prevents inheritance Animal( ) {... } //
Topic 6 Generic Data Structures "Get your data structures correct first, and the rest of the program will write itself." - David Jones.
1 Topic 4 Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“
CS 307 Fundamentals of Computer Science ADTS and Generic Data Structures 1 Topic 12 ADTS, Data Structures, Java Collections and Generic Data Structures.
Inheritance and Polymorphism
CS221 - Computer Science II Polymorphism 1. CS221 - Computer Science II Polymorphism 2 Outline  Explanation of polymorphism.  Using polymorphism to.
CS221 - Computer Science II Polymorphism 1 Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is.
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
1 Abstract Classes “I prefer Agassiz in the abstract, rather than in the concrete.” CS Computer Science II.
CS221 - Computer Science II Polymorphism 1. CS221 - Computer Science II Polymorphism 2 Outline  Explanation of polymorphism.  Using polymorphism to.
Topic 4 Inheritance.
Programming in Java CSCI-2220 Object Oriented Programming.
Types in programming languages1 What are types, and why do we need them?
Java Basics Opening Discussion zWhat did we talk about last class? zWhat are the basic constructs in the programming languages you are familiar.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Generic Data Structures "Get your data structures correct first, and the rest of the program will write itself." - David Jones EE 422CGenerics 1.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Composition When one class contains an instance variable whose type is another class, this is called composition. Instead of inheritance, which is based.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Written by: Dr. JJ Shepherd
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 3 – Extending classes.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
OOP Basics Classes & Methods (c) IDMS/SQL News
1 Topic 5 Polymorphism "“Inheritance is new code that reuses old code. Polymorphism is old code that reuses new code.”
Class Inheritance Part II: Overriding and Polymorphism Corresponds with Chapter 10.
Modern Programming Tools And Techniques-I
Objects as a programming concept
JAVA MULTIPLE CHOICE QUESTION.
Chapter 4 Assignment Statement
Inheritance ITI1121 Nour El Kadri.
Advanced Programming in Java
Chapter 11 Inheritance and Polymorphism
Inheritance and Polymorphism
Java Generics.
Interfaces I once attended a Java user group meeting where James Gosling (Java's inventor) was the featured speaker. During the memorable Q&A session,
Chapter 3 Assignment Statement
Interfaces and Inheritance
Continuing Chapter 11 Inheritance and Polymorphism
Topic 6 Generic Data Structures
Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is new code that reuses old code. Polymorphism.
Generics.
Methods and Parameters
CMPE212 – Stuff… Exercises 4, 5 and 6 are all fair game now.
Designing for Inheritance
Topic 7 Interfaces I once attended a Java user group meeting where James Gosling (one of Java's creators) was the featured speaker. During the memorable.
Chapter 19 Generics Dr. Clincy - Lecture.
Java Programming Language
Polymorphism.
CS201: Data Structures and Discrete Mathematics I
Generics.
Topic 10 Abstract Classes “I prefer Agassiz in the abstract,
Topic 4 Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“
Sridhar Narayan Java Basics Sridhar Narayan
Topic 5 Polymorphism "“Inheritance is new code that reuses old code. Polymorphism is old code that reuses new code.”
Topic 10 Abstract Classes “I prefer Agassiz in the abstract,
Fall 2018 CISC124 2/24/2019 CISC124 Quiz 1 marking is complete. Quiz average was about 40/60 or 67%. TAs are still grading assn 1. Assn 2 due this Friday,
Focus of the Course Object-Oriented Software Development
Java Programming Language
Review: libraries and packages
CMPE212 – Reminders Quiz 1 marking done. Assignment 2 due next Friday.
Java Programming: From the Ground Up
Chap 2. Identifiers, Keywords, and Types
Final and Abstract Classes
Agenda Types and identifiers Practice Assignment Keywords in Java
Presentation transcript:

Polymorphism

CS 221 - Computer Science II Outline Explanation of polymorphism Use polymorphism to make generic data structures CS 221 - Computer Science II

CS 221 - Computer Science II Data Type All class variables have: a declared type: Also called the static type. a dynamic type. What is the actual type of the object pointed to at run time or when a particular statement is executed? CS 221 - Computer Science II

CS 221 - Computer Science II Polymorphism Another key feature of OOP. Literally “having many forms.” Declared types in Java are polymorphic. Declared types can refer to: the declared/static type of the variable OR any descendants of the declared type. Rectangle r = new Rectangle(); r = new Square();//sub-class legal! CS 221 - Computer Science II

CS 221 - Computer Science II Dynamic Types Declared types refer to any valid class type, including abstract classes and interfaces. Dynamic types can only refer to instantiable classes (i.e. any class that’s not abstract or an interface). Shape s; // abstract class s = new Shape(); //illegal! CS 221 - Computer Science II

CS 221 - Computer Science II Question Consider the following class declarations: public class BoardSpace public class Property extends BoardSpace public class Street extends Property public class Railroad extends Property Which of the following statements would cause a syntax error, assuming all classes have a default constructor? A. Object obj = new Railroad(); B. Street s = new BoardSpace(); C. BoardSpace b = new Street(); D. Railroad r = new Street(); E. More than one of these CS 221 - Computer Science II

CS 221 - Computer Science II Question Consider the following class declarations: public class BoardSpace public class Property extends BoardSpace public class Street extends Property public class Railroad extends Property Which of the following statements would cause a syntax error, assuming all classes have a default constructor? A. Object obj = new Railroad(); B. Street s = new BoardSpace(); C. BoardSpace b = new Street(); D. Railroad r = new Street(); E. More than one of these. CS 221 - Computer Science II

Legality of Method Calls Method calls are syntactically legal if the method is in the declared type or any ancestor of the declared type The actual method that is executed at runtime is based on the dynamic type. dynamic dispatch CS 221 - Computer Science II

CS 221 - Computer Science II What’s the Output? Shape s = new Rectangle(1,2); System.out.println(s.toString()); s = new Rectangle(2, 3, 4, 5); System.out.println(s.toString()); s = new Circle(4, 5, 10); System.out.println(s.toString()); s = new Shape(); System.out.println(s.toString()); CS 221 - Computer Science II

CS 221 - Computer Science II What’s the Output? Shape s = new Rectangle(1,2); System.out.println(s.toString()); x: 0 y: 0 width: 1 height: 2 s = new Rectangle(2, 3, 4, 5); System.out.println(s.toString()); x: 2 y: 3 width: 4 height: 5 s = new Circle(4, 5, 10); System.out.println(s.toString()); x: 4 y: 5 radius: 10 s = new Shape(); System.out.println(s.toString()); Error: won’t compile CS 221 - Computer Science II

CS 221 - Computer Science II Method LookUp To determine if a method is legal, the compiler looks in the class based on the declared type. If it finds it, great. If not, goes to the super class and looks there. Continues until the method is found, or the Object class is reached, then throws a compilation error. To determine which method is actually executed at runtime: Starts with the actual run-time class of the object calling the method. Searches the class for that method. If found, executes it. Otherwise, goes to the super class and keeps looking. Repeats until a version is found. Is it possible the runtime system won’t find a method? CS 221 - Computer Science II

CS 221 - Computer Science II Question 2 What is output by the code to the right? A. !!live B. !eggegg C. !egglive D. !!! E. eggegglive public class Animal { public String talk(){ return "!"; } } public class Mammal extends Animal { public String talk(){ return "live"; } } public class Platypus extends Mammal { public String talk(){ return "egg"; } Animal a1 = new Animal(); Animal a2 = new Platypus(); Mammal m1 = new Platypus(); System.out.print(a1.talk()); System.out.print(a2.talk()); System.out.print(m1.talk()); CS 221 - Computer Science II

CS 221 - Computer Science II Question 2 What is output by the code to the right? A. !!live B. !eggegg C. !egglive D. !!! E. eggegglive public class Animal { public String talk(){ return "!"; } } public class Mammal extends Animal { public String talk(){ return "live"; } } public class Platypus extends Mammal { public String talk(){ return "egg"; } Animal a1 = new Animal(); Animal a2 = new Platypus(); Mammal m1 = new Platypus(); System.out.print( a1.talk() ); System.out.print( a2.talk() ); System.out.print( m1.talk() ); CS 221 - Computer Science II

CS 221 - Computer Science II Generic Types CS 221 - Computer Science II

CS 221 - Computer Science II An Array-Based List Don't want to have to write a new list class for every data type we want to store in lists. Moved to an array of Objects to store the elements of the list. // from array-based list public class List { private Object[] data; … } CS 221 - Computer Science II

CS 221 - Computer Science II Using the Object Class In Java, all classes inherit from exactly one other class, except Object. Object variables can refer to objects of their declared type and any descendants. polymorphism Thus, if the internal storage container is of type Object, it can hold anything, including primitive data types. CS 221 - Computer Science II

CS 221 - Computer Science II Wrapper Classes Primitive Type Wrapper Type int Integer double Double char Character boolean Boolean float Float byte Byte short Short long Long Primitive wrapper class is a class that encapsulates, or wraps, data types from the eight primitive data types. These classes can be used to instantiate objects representing primitive data types. CS 221 - Computer Science II

Difficulties with Object Creating generic containers using the Object data type and polymorphism is relatively straightforward. Using these generic containers leads to some difficulties: Casting Type checking CS 221 - Computer Science II

CS 221 - Computer Science II Question 1 What is output by the following code? List list = new List(); // 1 String name = "Olivia"; list.add(name); // 2 System.out.print(list.get(0).charAt(2));// 3 A. i B. No output due to syntax error at line // 1. C. No output due to syntax error at line // 2. D. No output due to syntax error at line // 3. E. No output due to runtime error. CS 221 - Computer Science II

CS 221 - Computer Science II Question 1 What is output by the following code? List list = new List(); // 1 String name = "Olivia"; list.add(name); // 2 System.out.print(list.get(0).charAt(2));// 3 A. i B. No output due to syntax error at line // 1. C. No output due to syntax error at line // 2. D. No output due to syntax error at line // 3. E. No output due to runtime error. CS 221 - Computer Science II

CS 221 - Computer Science II Code Example - Casting List list = new List(); String name = "Olivia"; list.add(name); System.out.print(list.get(0).charAt(2)); // Causes syntax error – declared type // Object does not have a charAt method // Must cast to a String System.out.println(((String)list.get(0)).charAt(2)); CS 221 - Computer Science II

Code Example – Type Checking //assume all elements of list are Strings public void printFirstChar(List list) { String temp; for(int i = 0; i < list.size(); i++) temp = (String)list.get(i); if(temp.length() > 0) System.out.println(temp.charAt(0)); } // What happens if not Strings? CS 221 - Computer Science II

CS 221 - Computer Science II Too Generic? Does the compiler allow this? List list = new List(); list.add("Olivia"); list.add(new Integer(12)); list.add(new Rectangle()); list.add(new List()); Yes No CS 221 - Computer Science II

CS 221 - Computer Science II Too Generic? Does the compiler allow this? List list = new List(); list.add("Olivia"); list.add(new Integer(12)); list.add(new Rectangle()); list.add(new List()); Yes No CS 221 - Computer Science II

Is this a Bug or a Feature? On September 9, 1945, a Harvard technical team looked at Panel F and found something unusual between points in Relay 70. It was a moth, which they promptly removed and taped in the log book. Grace Hopper added the caption "First actual case of bug being found," and that's the first time anyone used the word bug to describe a computer glitch. Naturally, the term debugging followed. Inventors and engineers had been talking about bugs for more than a century before the moth in the relay incident. Even Thomas Edison used the word. Word nerds trace the word bug to an old term for a monster -- it's a word that has survived in obscure terms like bugaboo and bugbear and in a mangled form in the word boogeyman. Like gremlins in machinery, system bugs are malicious. Anyone who spends time trying to get all the faults out of a system knows how it feels: After a few hours of debugging, any problems that remain are hellspawn, mocking attempts to get rid of them with a devilish glee. Moth in the machine: Debugging the origins of 'bug' Did Grace Hopper really invent the term 'bug' to describe software errors? By Computerworld staff https://www.computerworld.com/article/2515435/app-development/moth-in-the-machine--debugging-the-origins-of--bug-.html CS 221 - Computer Science II

CS 221 - Computer Science II "Fixing" the Method //assume all elements of are Strings public void printFirstChar(ArrayList list) { String temp; for(int i = 0; i < list.size(); i++) if(list.get(i) instanceof String) temp = (String)list.get(i); if(temp.length() > 0) System.out.println(temp.charAt(0)); } CS 221 - Computer Science II

CS 221 - Computer Science II Generic Types Java has syntax for parameterized data types. Referred to as Generic Types. A traditional parameter has a data type and can store various values just like a variable. public void foo(int x) Generic Types are like parameters, but the data type for the parameter is a data type. It’s like a variable that stores a data type. This is an abstraction. Actually, all data type info is erased at compile time. CS 221 - Computer Science II

Making our List Generic Data type variables declared in class header. // from generic array-based list public class List<T> { private T[] data; … } The <T> is the declaration of a data type parameter for the class. Represents any legal class: Foo, MyClass, String, Double, Circle, etc. CS 221 - Computer Science II

Making our List Generic The value T will be filled in whenever a programmer creates a new object. List<String> list = new List<String>(); The effect is to create a String array to store data in. CS 221 - Computer Science II

CS 221 - Computer Science II Using Generic Types // list stores Strings List<String> list = new List<String>(); list.add("Isabelle"); System.out.println(list.get(0).charAt(2)); //OK list.add(new Rectangle()); // syntax error CS 221 - Computer Science II

Generic Types and Subclasses List<Shape> list = new List<Shape>(); list.add(new Rectangle()); // OK list.add(new Square()); // OK list.add( new Circle()); // OK list above can store Shape objects and any descendants of Shape. That’s polymorphism! CS 221 - Computer Science II

CS 221 - Computer Science II Why Bother? Polymorphism allows code reuse in another way. Inheritance and polymorphism allow programmers to create generic data structures. CS 221 - Computer Science II

CS 221 - Computer Science II