forked from dr-cs/intro-oop-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAnimals.java
More file actions
40 lines (35 loc) · 1.06 KB
/
Animals.java
File metadata and controls
40 lines (35 loc) · 1.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
public class Animals {
public static abstract class Animal {
public abstract void speak();
}
public static class Mammal extends Animal {
public void speak() {
System.out.println("Hello!");
}
}
public static class Dog extends Mammal {
public void speak() {
System.out.println("Woof, woof!");
}
public void wagTail() {
System.out.println("(wags tail)");
}
}
public static class Cat extends Mammal {
public void speak() {
System.out.println("Meow!");
}
}
public static void main(String[] args) {
Mammal fido = new Dog();
fido.speak();
// Dog fido2 = fido; // Won't compile: Java won't implicitly downcast
((Mammal) fido).speak();
Mammal mittens = (Mammal) new Cat(); // Safe
Mammal sparky = new Mammal();
// Compiles, but will cause a ClassCastException at run-time,
Dog huh = (Dog) sparky;
// so we won't even get here.
huh.wagTail();
}
}