Polymorphism & Methods COMP206 Geoff Holmes & Bernhard Pfahringer (these slides: lots of input from Mark Hall) poly + morphos (greek) “many forms”

Slides:



Advertisements
Similar presentations
SUMMARY: abstract classes and interfaces 1 Make a class abstract so instances of it cannot be created. Make a method abstract so it must be overridden.
Advertisements

METHOD OVERRIDING 1.Sub class can override the methods defined by the super class. 2.Overridden Methods in the sub classes should have same name, same.
Module 8 “Polymorphism and Inheritance”. Outline Understanding Inheritance Inheritance Diagrams Constructors in Derived Classes Type Compatibility Polymorphism.
Polymorphism. The term polymorphism literally means "having many forms" A polymorphic reference is a variable that can refer to different types of objects.
C12, Polymorphism “many forms” (greek: poly = many, morphos = form)
Georgia Institute of Technology Workshop for CS-AP Teachers Chapter 3 Advanced Object-Oriented Concepts.
Objectives Introduction to Inheritance and Composition (Subclasses and SuperClasses) Overriding (and extending), and inheriting methods and constructors.
Slides 4/22 COP Topics Final Exam Review Final Exam The final exam is Friday, April 29 th at 10:00 AM in the usual room No notes, books, calculators,
SE-1020 Dr. Mark L. Hornick 1 Inheritance and Polymorphism: Abstract Classes The “not quite” classes.
C HAPTER 7 Better Living in Objectville. O VERVIEW Understanding Inheritance Designing an Inheritance Tree Avoiding Duplicate Code Overriding Methods.
Exam Objective : Demonstrate the use of polymorphism PRESENTED BY: SRINIVAS VG.
Polymorphism & Methods COMP204 Bernhard Pfahringer (with lots of input from Mark Hall) poly + morphos (greek) “many forms”
Creating Classes from Other Classes Chapter 2 Slides by Steve Armstrong LeTourneau University Longview, TX  2007,  Prentice Hall.
 In inheritance the child (subclass) chooses its parent (superclass)  Remember - only public or “protected” methods and variables are inherited  Should.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
Java Generics.
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
Generic types for ArrayList Old Java (1.4 and older): ArrayList strings = new ArrayList(); strings.enqueue(“hello”); String word = (String) strings.get(0);
Java Generics. 2 The Dark Ages: Before Java 5 Java relied only on inclusion polymorphism  A polymorphism code = Using a common superclass Every class.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
1 Inheritance and Polymorphism. 2 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
(c) University of Washington03-1 CSC 143 Java Inheritance Reading: Ch. 10.
Object oriented design in Java (useful revision for final exam)
LECTURE 07 Programming using C# Inheritance
CSE 331 Software Design & Implementation Hal Perkins Autumn 2012 Java Classes, Interfaces, and Types 1.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
Generics In Java 1.5 By Manjunath Beeraladinni. Generics ➲ New feature in JDK1.5. ➲ Generic allow to abstract over types. ➲ Generics make the code clearer.
CSC 142 O 1 CSC 142 Java More About Inheritance & Interfaces [Reading: chapter 13]
1 Java Inheritance. 2 Inheritance On the surface, inheritance is a code re-use issue. –we can extend code that is already written in a manageable manner.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Generalized Containers CSIS 3701: Advanced Object Oriented Programming.
Effective Java: Generics Last Updated: Spring 2009.
What is inheritance? It is the ability to create a new class from an existing class.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
Inheritance and Polymorphism Daniel Liang, Introduction to Java Programming.
RIT Computer Science Dept. Goals l Inheritance l Modifiers: private, public, protected l Polymorphism.
Parameters… Classes Cont Mrs. C. Furman October 13, 2008.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Inheritance and Access Control CS 162 (Summer 2009)
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
Generic(Parameterized ) types Mehdi Einali Advanced Programming in Java 1.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
SOEN 343 Software Design Section H Fall 2006 Dr Greg Butler
Coming up: Inheritance
29-July-2002cse Inheritance © 2002 University of Washington1 Inheritance CSE 142, Summer 2002 Computer Programming 1
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
CS1101 Group1 Discussion 6 Lek Hsiang Hui comp.nus.edu.sg
Basic Object-Oriented concepts. Concept: Classes describe objects Every object belongs to (is an instance of) a class An object may have fields –The class.
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)
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
Polymorphism 1. Reuse of code: every time a new sub-class is defined, programmers are reusing the code in a super-class. All non-private members of a.
BY:- TOPS Technologies
Comp1004: Inheritance II Polymorphism. Coming up Inheritance Reminder Overriding methods – Overriding and substitution Dynamic Binding Polymorphism –
Geoff Holmes and Bernhard Pfahringer COMP206-08S General Programming 2.
Inheritance a subclass extends the functionality of a superclass a subclass inherits all the functionality of a superclass don't reinvent the wheel – "stand.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Polymorphism and access control. RHS – SOC 2 What is polymorphism? In general: the ability of some concept to take on different forms In Java: the ability.
Design issues for Object-Oriented Languages
Modern Programming Tools And Techniques-I
OOP: Encapsulation &Abstraction
Inheritance and Polymorphism
ATS Application Programming: Java Programming
Java Programming Language
Polymorphism and access control
Object Oriented Programming
COMP204 Bernhard Pfahringer (with input from Robi Malik)
Presentation transcript:

Polymorphism & Methods COMP206 Geoff Holmes & Bernhard Pfahringer (these slides: lots of input from Mark Hall) poly + morphos (greek) “many forms”

Overriding Subclass redefines a method: –different behaviour –or maybe modified behaviour class Rectangle { public String toString() { return “ ”; }

Inheritance Subclasses inherit everything from superclasses, but cannot directly access private fields or methods, only public and protected ones. Can still access overridden methods: public void roam() { super.roam(); // some additional local stuff }

Inheritance: Is-A (not Has-A) B should extend A if “B is-A A” –Triangle Is-A Shape –Surgeon Is-A Medical Doctor Bathroom Has-A Tub –Tub is an instance variable of Bathroom (Composition)

Code Inheritance Use inheritance to implement shared behaviour (code) only once! Always avoid code duplication! –easier to change (only one place), especially when debugging

Polymorphism what happens when one declares and initializes a reference variable: Dog myDog = new Dog(); allocate space for reference variable of type Dog allocate space for a new Dog object on the heap (and initialize it) point the reference to the new object

Polymorphism Reference type can be any super class or Interface implemented by actual type: Animal myDog = new Dog(); As generic as possible => more flexible code: Map myMap = new HashMap ();

Polymorphism Animal[] animals = new Animal[]{new Dog(), new Lion(), new Cat(), new Wolf(), new Hippo()}; for(Animal a: animals) { a.eat(); a.roam(); }

Polymorphism Parameters/Arguments and return values can be polymorphic too: class Vet { public void giveShot(Animal a) { a.makeNoise(); } class PetOwner { public void start() { Vet v = new Vet(); Dog d = new Dog(); Hippo h = new Hippo(); v.giveShot(d); v.giveShot(h); }

How to stop overriding: final declaration: –class: cannot extend/subclass any further final public class String {.. } –method: cannot be overridden in subclasses class Cat { final public void makeNoise() {…} –field: cannot change value final int count = animals.length;

Overriding rules Argument and return type must be the same: class Appliance { public boolean turnOn(); } class Toaster extends Appliance { public boolean turnOn(int level); // OVERLOADING }

Overriding rules May NOT be less accessible: class Appliance { public boolean turnOn(); } class Toaster extends Appliance { protected boolean turnOn(); // illegal }

Overloading Two (or more) methods with the same name but different argument lists (see code example) Usually best avoided, can be very confusing and counter-intuitive

Which method is executed Compile time: compiler ensures that method with appropriate signature (compile-time type info for arguments) exists in “compile-time” receiver class Runtime: given the actual runtime-type of the receiver, the most specific method of appropriate signature is located and executed ==> runtime types of arguments do NOT matter (again, see code examples)

Java Generics (with input from Robi Malik)

Generic types for collections Old Java (1.4 and older): List strings = new ArrayList(); strings.add(“hello”); String word = (String) strings.get(0); New (since 1.5): List strings = new ArrayList (); strings.add(“hello”); String word = strings.get(0);

Advantages Better readability Better type-safety: no casts (runtime checks), compiler can already catch problems

Writing your own generic code public class Stack { public void push(E element) { contents.add(element); } public E pop() { int top = contents.size()-1; E result = contents.get(top); contents.remove(top); return result; } private List contents = new ArrayList (); }

Formal type parameter public class Stack { … } –convention: Short (single-char) uppercase –can be used wherever a Type is needed –will be replaced with actual Type

Problems with sub-types class Student extends Person {.. } List students = new ArrayList (); List people = students; // should this be possible? -> no

No, because Person sam = new Person(); people.add(sam); // if this was legal, we would have just sneaked a non- student onto the students list on the other hand, how do you write generic code then accepting lists of sub-types of Persons ???

Wildcards void printCollection(Collection c) { for(Object o: c) { System.out.println(o); } // only read access (everything is an Object), but cannot add, because do not know correct type (except null, which is any type)

Bounded wildcards public void drawAll(Collection c) { for(Shape shape: c) { shape.draw(); } // again, only read access, allows collections of Shape or any sub type of Shape