Upward transformation
Anyway, you can use the Fu
type to refer to the Zi
type
1. At the time of definition
Fu fu = new Zi
2. When the collection uses generics
List<String> list = new ArrayList();
list.add("123");//String 被转换为Object
3. When transferring parameters
Zi zi = new Zi(); //创建一个子类
void fn(Fu fu){
}; //定义一个父类型参数的方法
fn(zi);//传入zi
Downcast
Polymorphism allows us to easily use the subclass method of the same name, but we cannot use the unique method of the subclass, so we need to downcast to the subclass and call it later.
package com;
import java.util.LinkedList;
import java.util.List;
public class App2 {
public static void main(String[] args) {
List<Object> list = new LinkedList<>();
list.add("123");
// System.out.println(list.get(0).charAt()); //error charAt是String独有的方法
Object a= list.get(0);
System.out.println(a instanceof Object); // true
System.out.println(a instanceof String); // true 既是Object 又是String 类型,所以可以从Object转换为String类型
System.out.println(((String) a).charAt(0));
}
}