How to correctly perform upcasting and downcasting in J…

In Java, upcasting refers to assigning a subclass object to a superclass reference variable, while downcasting refers to forcibly converting a superclass reference variable to its subclass object.

Example of upward transformation:

class Animal {
    public void sound() {
        System.out.println("Animal makes sound");
    }
}

class Dog extends Animal {
    public void sound() {
        System.out.println("Dog barks");
    }
}

public class Main {
    public static void main(String[] args) {
        Dog dog = new Dog(); // 创建子类对象
        Animal animal = dog; // 向上转型,将子类对象赋值给父类引用变量
        animal.sound(); // 调用父类引用变量的方法会执行子类的方法
    }
}

The output result is:

Dog barks

An example of downcasting:

class Animal {
    public void sound() {
        System.out.println("Animal makes sound");
    }
}

class Dog extends Animal {
    public void sound() {
        System.out.println("Dog barks");
    }
    
    public void fetch() {
        System.out.println("Dog fetches");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal animal = new Dog(); // 创建父类引用变量指向子类对象
        Dog dog = (Dog) animal; // 向下转型,强制将父类引用变量转换为子类对象
        
        dog.fetch(); // 调用子类对象的方法
    }
}

The result is:

Dog fetches

It’s important to note that there is a risk in downcasting. If the actual object that a parent class reference variable points to is not the type it is being cast to, it can lead to a runtime exception. Therefore, when performing downcasting, it is best to first use the instanceof operator to determine if the reference variable can be cast to the target type in order to avoid runtime exceptions.

if (animal instanceof Dog) {
    Dog dog = (Dog) animal;
    dog.fetch();
} else {
    System.out.println("Cannot downcast to Dog");
}
bannerAds