Encapsulation!
The “is a” rule:
Object1, Object2
Object2 is a Object1, then it might make sense to define Object2 as a subclass of Object1
Apple is a Fruit, so maybe define class Apple extends Fruit
public abstract class Animal {
private String name;
public Animal (String name) { this.name = name; }
public String getName () { return name; }
public abstract String getSpecies ();
public void feed () {
System.out.println("You just fed " + name + " the " + getSpecies()
+ " some " + getFavoriteFood() + "!");
}
public abstract String getFavoriteFood ();
public abstract void printAnimalFact ();
}
Write a class that extends Animal
abstract methodsDog might have a bark() method that prints Woof! to System.out.A zoo with one type of animal:
public class Zoo {
public static final int ZOO_SIZE = 10;
public static void main(String[] args) {
Platypus[] animals = new Platypus[ZOO_SIZE];
for (int i = 0; i < animals.length; i++) {
animals[i] = new Platypus(Names.getRandomName());
}
for (int i = 0; i < animals.length; i++) {
animals[i].feed();
}
}
}
How can we store different types of animal in our zoo?
animals to be an array of Animal:Animal[] animals = new Animal[ZOO_SIZE];
animals to be the desired type of Animal:animals[0] = new Platypus(Names.getRandomName());
animals[1] = new Dog(Names.getRandomName());
...
Animal[] animals = new Animal[ZOO_SIZE];
animals[0] = new Platypus(Names.getRandomName());
animals[1] = new Dog(Names.getRandomName());
...
animals[i] stores a reference to an Animal
Platypus is type of Animal
Platypus extends AnimalAnimal class…The entries in animals are (references to) Animals
Animal
Platypuses, some are Dogs, …This is polymorphism
We can see polymorphism using the instanceof keyword
alice instanceof Animal returns true if alice is an Animal
alice instanceof Platypus returns true if alice is a Platypus
For example
if (alice instanceof Animal) {
System.out.println("Alice is an Animal!");
}
if (alice instanceof Platypus) {
System.out.println("Alice is a Platypus");
}
What happens if call alice.sting()?
alice refers to a Platypus
Platypus has a method sting()
alice refers to an Animal that is a Platypus
sting() right?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 Platypus("Alice");
alice.sting();
alice is treated as a reference to an Animal, not a Platypus
Platypus: Platypus aliceToo = (Platypus) alice; // cast alice a ref to Platypus
aliceToo.sting(); // this works now!
animals[0] is a Platypus, it should sting()
instanceof
if (animals[i] instanceof Platypus) {
Platypus p = (Platypus) animals[i];
p.sting();
}