Java 多态之向上转型与向下转型
代码示例
父类:
public class Father {
int f = 100;
public void name(){
System.out.println("father");
}
public void tel(){
System.out.println("12345");
}
}
子类:
public class Son extends Father{
int s = 200;
public void name(){
System.out.println("son");
}
public void sex(){
System.out.println("man");
}
}
测试方法:
public static void main(String[] args) {
Father a = new Son();
a.name(); //输出son
a.tel();
a.f = 10;
// a.sex(); 报错,需要写成((Son) a).sex();
// a.s = 20; 报错,需要写成((Son) a).s = 20;
Father b = new Son(); //先向上转型
Son c = (Son)a; //再进行向下转型,强制转换
c.name(); //输出son
c.sex(); //输出man
c.tel();
c.f = 1000;
c.s = 2000;
System.out.println(a instanceof Son); //输出true
System.out.println(a instanceof Father); //输出true
System.out.println(c instanceof Son); //输出true
System.out.println(c instanceof Father); //输出true
}
向上转型
向上转型,即父类引用指向子类对象,例:
Father a = new Son(); //向上转型
向上转型后的效果:
- 可以调用父类的所有方法,如果子类重写了父类的方法,则调用子类的方法,子类特有的方法无法调用。
- 可以调用父类的属性,不可以调用子类的属性。
向上转型的作用:
- 减少部分重复代码。
- 根据不同的需求进行对象实例化。
向下转型
向下转型的前提条件是先进行了向上转型,例:
Father b = new Son(); //先向上转型
Son c = (Son)a; //再进行向下转型,强制转换
没有经过向上转型,会提示编译错误。
向下转型后的效果:
- 可以调用子类的所有方法。
- 可以调用子类的属性。
向下转型的作用:
- 通过向下转型,实例对象能够重新调用子类独有方法(向上转型时,会遗失子类对象独有的其他方法)。
instanceof 关键字
instanceof:用来判断左边对象是否属于右边的类或者右边类的子类的实例对象,例:
System.out.println(a instanceof Son); //输出true
System.out.println(a instanceof Father); //输出true
System.out.println(c instanceof Son); //输出true
System.out.println(c instanceof Father); //输出true
返回类型是布尔(boolean)类型。
需要用到对象的强制类型转换时,需要使用instanceof进行判断。