Java Superclass to Subclass Casting Guide

In Java, a superclass object can be cast to a subclass object through type casting, provided that the superclass object is actually an instance of the subclass.

The example code is as follows:

// 定义父类
class Parent {
    // 父类方法
    public void parentMethod() {
        System.out.println("This is parent method");
    }
}

// 定义子类
class Child extends Parent {
    // 子类方法
    public void childMethod() {
        System.out.println("This is child method");
    }
}

public class Main {
    public static void main(String[] args) {
        // 创建父类对象
        Parent parent = new Parent();
        
        // 将父类对象强制类型转换为子类对象
        Child child = (Child) parent;
        
        // 调用子类方法
        child.childMethod();
    }
}

Please note that performing a type cast on a parent class object that is not actually an instance of the subclass will result in a runtime exception of ClassCastException. Therefore, before performing a type cast, it is important to first confirm that the parent class object is actually an instance of the subclass.

bannerAds