Object classZoo
Polymorphism!
Animal alice = new Elephant("Alice");
alice instanceof Animal // returns true
alice instanceof Elephant // also returns true
Animal:Animal zoo[] = new Animal[2];
zoo[0] = new Elephant("Alice");
zoo[1] = new Platypus("Bob");
We have an array of different Animals…
Animal zoo[] = new Animal[2];
zoo[0] = new Elephant("Alice");
zoo[1] = new Platypus("Bob");
Animals do different thingszoo[0].feed() calls Elephant version of feed
zoo[1].feed() calls Platypus version of feed
Elephant and Platypus?
Elephant can trumpet()
Platypus can sting()
… if we call
zoo[0].trumpet(); // zoo[0] is an Elephant
zoo[1].sting(); // zoo[1] is a Platypus
Zoo.java:23: error: cannot find symbol
zoo[0].trumpet();
^
symbol: method sting()
location: class Animal
1 error
The reason:
zoo is declared to be an array of Animals
trumpet() is not declared for Animal
feed() is declared in Animal)zoo[0] is an Elephant, the compiler complains because zoo[0] wasn’t declared as an Elephant.
What is the point of having a Zoo if your Elephants can’t trumpet()?
int n = 10;
double d = n; // java thinks this is okay
double d = 10.0;
int n = d;
gives
error: incompatible types: possible lossy conversion from double to int
We can force Java to do the conversion by casting:
double d = 10.0;
int n = (int) d; // truncates d (i.e., removes everything after the decimal)
class
sting is not defined for Animal
Animal alice = new Elephant("Alice");
alice.trumpet();
alice is treated as a reference to an Animal, not an Elephant
Elephant: Elephant aliceToo = (Elephant) alice; // cast alice a ref to Platypus
aliceToo.trumpet(); // this works now!
Zoo
We can
Animals are ElephantsAnimal as an Elephant, then have it trumpet()
for (int i = 0; i < animals.length; i++) {
animals[i].feed();
if (animals[i] instanceof Elephant) {
Elephant e = (Elephant) animals[i];
e.trumpet();
}
The Java compiler will let you cast as any sub-class of Animal:
for (int i = 0; i < animals.length; i++) {
animals[i].feed();
if (animals[i] instanceof Platypus) {
Elephant e = (Elephant) animals[i];
e.trumpet();
}
}
Exception in thread "main" java.lang.ClassCastException: class Platypus cannot be cast to class Elephant (Platypus and Elephant are in unnamed module of loader 'app')
at Zoo.main(Zoo.java:19)
Object class class MyClass extends SomeClass, AnotherClass {...}
How to depict relationship between Shape, Circle, Rectangle, Ellipse, Square, Quadrilateral, Triangle?
Object: The Mother of all ClassesEvery class in Java is automatically a subclass of Object
Object:
boolean equals(Object obj)String toString()Why is this good?