Java父类强制转换子类原则
image 最近,微信群友在讨论子类父类的转换问题,其实不难,给大家用实例来说明一下就很明了了。 我们知道Java中子类转换成父类是没有任何问题的,那父类可以转换成子类吗? 来看下面这段程序: public class TestObjectConvert { public static void main(String[] args) { test1(); test2(); } private static void test1() { Fruit fruit1 = new Fruit(); Apple apple1 = new Apple(); apple1 = (Apple) fruit1; // java.lang.ClassCastException } private static void test2() { Fruit fruit1 = new Apple(); Apple apple1 = new Apple(); apple1 = (Apple) fruit1; } static class Fruit { } static class Apple extends F...