1、直接赋值
public static void main(string[] args) { //父类引用 引用了 子类引用所引用的对象 animal animal = new cat();;//向上转型}
2、方法传参,把一个cat的子类传给一个animal类型的父类,这里也是能发生向上转型的。
public class test extends testdemo { public static void func(animal animal) { } public static void main(string[] args) { //父类引用 引用了 子类引用所引用的对象 cat cat = new cat(); func(cat); }}
3、方法返回,func方法的返回类型是animal,但返回的确是一个cat类型,这里也是发生了向上转型。
public class test extends testdemo { public static animal func() { cat cat = new cat(); return cat; } public static void main(string[] args) { animal animal = func(); }}
以上就是java向上转型发生的时机是什么的详细内容。