加载中...
加载中...
Java父类强制转换子类原则

Java父类强制转换子类原则 原创

我们知道Java中子类转换成父类是没有问题的,那父类可以转换成子类吗? 

复制javapublic class ObjectConvert {

public static void main(String[] args) {
test1();
test2();
}

private static void test1() {
Fruit fruit1 = new Fruit();
Apple apple1 = new Apple();
apple1 = (Apple) fruit1;
}

private static void test2() {
Fruit fruit1 = new Apple();
Apple apple1 = new Apple();
apple1 = (Apple) fruit1;
}

static class Fruit {}
static class Apple extends Fruit {}
}
  • 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
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52

结果:

test1:类转异常;
test2:转换正常。

想让父类强制转换成子类,必须满足:父类是子类构造出来的实例,不然是不能强转的。

也就是父类只有该子类对应的实例才能强转。



没有更多推荐了 [去首页]
image
文章
376
原创
293
转载
83
翻译
0
访问量
183411
喜欢
73
粉丝
5
码龄
7年
资源
3

文章目录

加载中...
0
0