Polymorphism 15-Nov-18.

Slides:



Advertisements
Similar presentations
C12, Polymorphism “many forms” (greek: poly = many, morphos = form)
Advertisements

CS 106 Introduction to Computer Science I 04 / 11 / 2008 Instructor: Michael Eckmann.
Java Inheritance. What is inherited A subclass inherits variables and methods from its superclass and all of its ancestors. The subclass can use these.
23-May-15 Polymorphism. 2 Signatures In any programming language, a signature is what distinguishes one function or method from another In C, every function.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
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,
Polymorphism. Legal assignments Widening is legal Narrowing is illegal (unless you cast) class Test { public static void main(String args[]) { double.
15-Jun-15 Polymorphism. 2 Signatures In any programming language, a signature is what distinguishes one function or method from another In C, every function.
19-Jun-15 Polymorphism. 2 Signatures In any programming language, a signature is what distinguishes one function or method from another In C, every function.
1 Inheritance Overview l Inheritance ensures Reusability l Example of Inheritance l What is actually Inherited? l Overloading Vs. Overriding l Object:
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
26-Jun-15 Polymorphism. 2 Legal assignments Widening is legal Narrowing is illegal (unless you cast) class Test { public static void main(String args[])
1 Inheritance and Polymorphism. 2 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common.
Inheritance Part II. Lecture Objectives To learn about inheritance To understand how to inherit and override superclass methods To be able to invoke superclass.
Day 4 Objectives Constructors Wrapper Classes Operators Java Control Statements Practice the language.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Inheritance and Polymorphism.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
Inheritance. Inheritance Early programmers often wrote code very similar to existing code Example: A human resources system might handle different types.
What is inheritance? It is the ability to create a new class from an existing class.
Inheritance and Polymorphism Daniel Liang, Introduction to Java Programming.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
28-Dec-04polymorhism.ppt1 Polymorphism. 28-Dec-04polymorhism.ppt2 signatures in any programming language, a signature is what distinguishes one function.
Inheritance and Access Control CS 162 (Summer 2009)
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
CS305j Introduction to Computing Classes II 1 Topic 24 Classes Part II "Object-oriented programming as it emerged in Simula 67 allows software structure.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Rina System development with Java Instructors: Rina Zviel-Girshin Lecture 7.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved COS240 O-O Languages AUBG,
Inheritance in Java. Access Specifiers private keywordprivate keyword –Used for most instance variables –private variables and methods are accessible.
AD Lecture #1 Object Oriented Programming Three Main Principles 1 Inheritance Encapsulation Polymorphism.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
(c) University of Washington06-1 CSC 143 Java Inheritance Tidbits.
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
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.
28-Dec-04polymorhism.ppt1 Polymorphism. 28-Dec-04polymorhism.ppt2 signatures in any programming language, a signature is what distinguishes one function.
BY:- TOPS Technologies
Comp1004: Inheritance II Polymorphism. Coming up Inheritance Reminder Overriding methods – Overriding and substitution Dynamic Binding Polymorphism –
Comp1004: Object Oriented Design I Abstract Classes and Interfaces.
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.
Chapter 11 Inheritance and Polymorphism
Chapter 7- Inheritance.
Agenda Warmup AP Exam Review: Litvin A2
Namespaces, Scopes, Access privileges
Week 8 Lecture -3 Inheritance and Polymorphism
Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is new code that reuses old code. Polymorphism.
Polymorphism 11-Nov-18.
Polymorphism 11-Nov-18.
Chapter 9 Inheritance and Polymorphism
Inheritance 2nd Lecture
The super Reference Constructors cannot be used in child classes, even though they have public visibility Yet we often want to use the parent's constructor.
Polymorphism and access control
Polymorphism 28-Nov-18.
Week 6 Object-Oriented Programming (2): Polymorphism
Inheritance 2nd Lecture
Testing and debugging A short interlude 2-Dec-18.
Inheritance 2nd Lecture
Java Inheritance.
Namespaces, Scopes, Access privileges
Polymorphism 15-Apr-19.
Testing and debugging A short interlude 17-Apr-19.
CSE 142 Lecture Notes Defining New Types of Objects, cont'd.
Polymorphism 21-Apr-19.
Chapter 11 Inheritance and Polymorphism
Special instance methods: toString
Chapter 11 Inheritance and Polymorphism Part 1
Chapter 11 Inheritance and Encapsulation and Polymorphism
CMSC 202 Inheritance II.
Classes and Methods 15-Aug-19.
Presentation transcript:

Polymorphism 15-Nov-18

Revision What is the return type of the equals method? void boolean Object String I am confused

String s = new String(“4”); s = 4; All of them (a) and (b) (b) and (c) Which version(s) are correct? String s = ‘4’ ; String s = “4” ; String s = (String) ‘4’ ; String s = new String(“4”); s = 4; All of them (a) and (b) (b) and (c) (b) and (d) (b) and (c) and (d)

Double, Integer, Float So what’s the deal with these capitalized versions? These are classes! int, double, float etc – these are primitives Primitives have no methods!! Java thinks only in terms of classes so the capitalized versions are ‘wrappers’ around the primitives

Double, Integer, Float Which one to use? Do you need an object? Do you want to convert back and forth between data types? Whenever it is a simple usage, stick to the primitives. Objects do come with extra overhead (not going into the details here)

Signatures In any programming language, a signature is what distinguishes one function or method from another In C, every function has to have a different name In Java, two methods have to differ in their names or in the number or types of their parameters foo(int i) and foo(int i, int j) are different foo(int i) and foo(int k) are the same foo(int i, double d) and foo(double d, int i) are different In C++, the signature also includes the return type But not in Java!

Polymorphism Polymorphism means many (poly) shapes (morph) In Java, polymorphism refers to the fact that you can have multiple methods with the same name in the same class There are two kinds of polymorphism: Overloading Two or more methods with different signatures Overriding Replacing an inherited method with another having the same signature

Overloading class Test { public static void main(String args[]) { myPrint(5); myPrint(5.0); } static void myPrint(int i) { System.out.println("int i = " + i); } static void myPrint(double d) { // same name, different parameters System.out.println("double d = " + d); } } int i = 5 double d = 5.0

Why overload a method? So you can use the same names for methods that do essentially the same thing Example: println(int), println(double), println(boolean), println(String), etc. So you can supply defaults for the parameters: int increment(int amount) { count = count + amount; return count; } int increment() { return increment(1); } Notice that one method can call another of the same name So you can supply additional information: void printResults() { System.out.println("total = " + total + ", average = " + average); } void printResult(String message) { System.out.println(message + ": "); printResults(); }

Have we already seen overloading? Is there an example of this in your current assignment?

DRY (Don’t Repeat Yourself) When you overload a method with another, very similar method, only one of them should do most of the work: void debug() { System.out.println("first = " + first + ", last = " + last); for (int i = first; i <= last; i++) { System.out.print(dictionary[i] + " "); } System.out.println(); } void debug(String s) { System.out.println("At checkpoint " + s + ":"); debug(); }

Legal assignments Widening is legal (going to more general data type) class Test { public static void main(String args[]) { double d; int i; d = 5; // legal i = 3.5; // illegal i = (int) 3.5; // legal } } Widening is legal (going to more general data type) Narrowing is illegal (unless you cast) All ints are doubles but all doubles are not ints, so Java gets mad unless you do the cast!

Legal method calls class Test { public static void main(String args[]) { myPrint(5); } static void myPrint(double d) { System.out.println(d); } } 5.0 Legal because parameter transmission is equivalent to assignment myPrint(5) is like double d = 5; System.out.println(d);

Illegal method calls class Test { public static void main(String args[]) { myPrint(5.0); } static void myPrint(int i) { System.out.println(i); } } myPrint(int) in Test cannot be applied to (double) Illegal because parameter transmission is equivalent to assignment myPrint(5.0) is like int i = 5.0; System.out.println(i);

Java uses the most specific method class Test { public static void main(String args[]) { myPrint(5); myPrint(5.0); } static void myPrint(double d) { System.out.println("double: " + d); } static void myPrint(int i) { System.out.println("int: " + i); } } int:5 double: 5.0

Multiple constructors I You can “overload” constructors as well as methods: Counter() { count = 0; } Counter(int start) { count = start; }

Multiple constructors II One constructor can “call” another constructor in the same class, but there are special rules You call the other constructor with the keyword this The call must be the very first thing the constructor does Point(int x, int y) { this.x = x; this.y = y; sum = x + y; } Point() { this(0, 0); } A common reason for overloading constructors is (as above) to provide default values for missing parameters Look at Rectangle.java for another example

Extending a class Use the actual word ‘extends’ class Square extends Rectangle class Goalkeeper extends Player As in Python, you get the methods of the base class (the parent class) for free You can only extend one class

Superclass construction I The very first thing any constructor does, automatically, is call the default constructor for its superclass class Foo extends Bar { Foo() { // constructor super(); // invisible call to superclass constructor ... You can replace this with a call to a specific superclass constructor Use the keyword super This must be the very first thing the constructor does class Foo extends Bar { Foo(String name) { // constructor super(name, 5); // explicit call to superclass constructor ...

Superclass construction II Unless you specify otherwise, every constructor calls the default constructor for its superclass class Foo extends Bar { Foo() { // constructor super(); // invisible call to superclass constructor ... You can use this(...) to call another constructor in the same class: class Foo extends Bar { Foo(String message) { // constructor this(message, 0, 0); // your explicit call to another constructor ...

Superclass construction III You can use super(...) to call a specific superclass constructor class Foo extends Bar { Foo(String name) { // constructor super(name, 5); // your explicit call to some superclass constructor ... Since the call to another constructor must be the very first thing you do in the constructor, you can only do one of the above

Overriding This is called overriding a method class Animal { public static void main(String args[]) { Animal animal = new Animal(); Dog dog = new Dog(); animal.print(); dog.print(); } void print() { System.out.println("Superclass Animal"); } } public class Dog extends Animal { void print() { System.out.println("Subclass Dog"); } } This is called overriding a method Method print in Dog overrides method print in Animal Superclass Animal Subclass Dog

How to override a method Create a method in a subclass having the same signature as a method in a superclass That is, create a method in a subclass having the same name and the same number and types of parameters Parameter names don’t matter, just their types Restrictions: The return type must be the same The overriding method cannot be more private than the method it overrides (ignore this bullet point for now)

Why override a method? Dog dog = new Dog(); System.out.println(dog); Prints something like Dog@feda4c00 The println method calls the toString method, which is defined in Java’s top-level Object class Hence, every object can be printed (though it might not look pretty) Java’s method public String toString() can be overridden If you add to class Dog the following: public String toString() { return name; } Then System.out.println(dog); will print the dog’s name, which may be something like: Fido

In class example of inheritance We have seen Rational Can we use Rational to create an Integer class? Whenever you are thinking about inheritance first answer the question Is every integer a rational number? Integers are Rationals with a denominator of 1! How to express this idea in Java? Since Integer already exists in Java, we will call the class Int to avoid confusion.

More about toString() It is almost always a good idea to override public String toString() to return something “meaningful” about the object When debugging, it helps to be able to print objects When you print objects with System.out.print or System.out.println, they automatically call the objects toString() method When you concatenate an object with a string, the object’s toString() method is automatically called You can explicitly call an object’s toString() method This is sometimes helpful in writing unit tests; however... Since toString() is used for printing, it’s something you want to be able to change easily (without breaking your test methods) It’s usually better to write a separate method, similar to toString(), to use in your JUnit tests

Equality Consider these two assignments: Thing thing1 = new Thing(); Thing thing2 = new Thing(); Are these two “Things” equal? That’s up to the programmer! But consider: Thing thing3 = new Thing(); Thing thing4 = thing3; Yes, because they are the same Thing!

The equals method Primitives can always be tested for equality with == For objects, == tests whether the two are the same object Two strings "abc" and "abc" may or may not be == ! Objects can be tested with the method public boolean equals(Object o) in java.lang. Unless overridden, this method just uses == It is overridden in the class String It is not overridden for arrays; == tests if its operands are the same array Morals: Never use == to test equality of Strings or arrays or other objects Use equals for Strings, java. util.Arrays.equals(a1, a2) for arrays If you test your own objects for equality, override equals Hands on overriding example with Rational and Polynomial

Calling an overridden method When your class overrides an inherited method, it basically “hides” the inherited method Within this class (but not from a different class), you can still call the overridden method, by prefixing the call with super. Example: super.printEverything(); You would most likely do this in order to observe the DRY principle The superclass method will do most of the work, but you add to it or adjust its results This isn’t a call to a constructor, and can occur anywhere in your class (it doesn’t have to be first)

Summary You should overload a method when you want to do essentially the same thing, but with different parameters You should override an inherited method if you want to do something slightly different than in the superclass It’s almost always a good idea to override public void toString() -- it’s handy for debugging, and for many other reasons To test your own objects for equality, override public void equals(Object o) There are special methods (in java.util.Arrays) that you can use for testing array equality