Java 觀念 - Type Casting

Type Casting 跟物件繼承很有關係,只要子類別繼承父類別,那他們就有 Casting 的關係。

直接看以下範例:

class Animal {
    void speak(){
        System.out.println("Default speak");
    }
}

class Bird extends Animal {
    @Override
    void speak() {
        System.out.println("ㄐㄐ");
    }
}

class Dog extends Animal {
    @Override
    void speak() {
        System.out.println("吉娃娃");
    }
}

public class main {
    public static void main(String[] args) {
        Animal animal = new Animal();
        Bird bird = new Bird();
        Dog dog = new Dog();

        animal.speak();
        bird.speak();
        dog.speak();

        // Upcasting and Downcasting

        Animal animal2;
        animal2 = bird; // Upcasting
        animal2.speak(); // works normally

        Bird bird2;
//        bird2 = animal; // Down casing, compile error
//        bird2 = (Bird)animal; // Compile pass
//        bird2.speak(); // but throw ClassCastException error

        Dog dog2;
//        dog2 = bird; // Obviously not working for compiling
//        dog2 = (Dog)bird; // Cannot casting to another child class, compile error.
    }
}

Revision #1
Created 28 June 2024 07:04:50 by Nesquate
Updated 28 June 2024 07:19:36 by Nesquate