Java Programming- Polymorphism
Signatures
2
Polymorphism
3
Overloading
4
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?
5
DRY (Don’t Repeat Yourself)
6
Another reason to overload methods
7
Legal assignments
8
class Test { � public static void main(String args[]) {� double d;� int i;� d = 5; // legal� i = 3.5; // illegal� i = (int) 3.5; // legal� }�}
Legal method calls
9
class Test { � public static void main(String args[]) {� myPrint(5);� }
static void myPrint(double d) {� System.out.println(d);� }�}
5.0
Illegal method calls
10
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)
Java uses the most specific method
11
Multiple constructors I
12
Multiple constructors II
13
Superclass construction I
14
Superclass construction II
15
Shadowing
16
class Animal { � String name = "Animal";� public static void main(String args[]) {� Animal animal = new Animal();� Dog dog = new Dog();� System.out.println(animal.name + " " + dog.name);� }�}
public class Dog extends Animal {� String name = "Dog";�}
Animal Dog
An aside: Namespaces
17
Overriding
18
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");� }�}
Superclass Animal�Subclass Dog
How to override a method
19
Why override a method?
20
More about toString()
21
Equality
22
The equals method
23
Calling an overridden method
24
Summary
25
Thank You