Java Code:
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 | public class Main { public static void main(String[] args) { class Animal { public String printName() { return "Animal"; } } class Dog extends Animal { public String printName() { return "Dog"; } } Animal animal = new Animal(); Dog dog = new Dog(); Animal unknown = (Animal) dog; System.out.println("animal: " + animal.printName()); System.out.println("dog: " + dog.printName()); System.out.println("unknown: " + unknown.printName()); } } |
Output:
1 2 3 4 5 | animal: Animal dog: Dog unknown: Dog |
Casting really means is taking an Object of one particular type and turning it into another Object type.