向上转型:当有子类对象赋值给一个父类引用时,多态自己就是向上转型的过程java
父类引用指向子类对象spa
父类类型 变量名 = new 子类类型(); 例如:Father father = new Son();//upcasting (向上转型), 对象引用指向一个Son对象
向下转型: 一个已经向上转型的子类对象能够使用强制类型转换的格式,将父类引用转为子类引用,这个过程是向下转型,向下转型必须以向上转型为前提。若是是直接建立父类对象,是没法向下转型的。code
子类引用指向父类对象,前提是已经进行了向上转型对象
子类类型 变量名 = (子类类型) 父类类型的变量; Son son = (Son) father; //downcasting (向下转型),father仍是指向Son对象
错误的状况:编译
Father f2 = new Father(); Son s2 = (Son) f2;//运行时出错,子类引用不能指向父类对象
向上转型与向下转型的使用:ast
package com.day04; /** * @author SFJ * @date 2019/11/10 * @time 21:48 **/ public class Test1 { public static void main(String[] args) { Person person = new Student();//向上转型 person.show();//调用子类重写方法 System.out.println(person.age); Student student = (Student)person;//向下转型(前提是已经向上转型) student.study();//调用子类特有方法 } } class Person { private String name = "Sangfengjiao"; int age = 21; public void show() { System.out.println(name); } } class Student extends Person { public String grade; int age = 22; public void show() { System.out.println("Studet:Sang fengjiao"); } public void study() { System.out.println("student should study"); } }
向上转型的做用:能够以父类做为参数,使代码变得简洁class
package com.day04; /** * @author SFJ * @date 2019/11/10 * @time 22:04 **/ public class Test2 { public static void main(String[] args) { doeat(new Male()); doeat(new Female()); } public static void doeat(Human human)//向上转型,子类对象做为参数 { human.eat(); } } class Human{ public void eat() { System.out.println("Human eat......"); } } class Male extends Human{ public void eat() { System.out.println("Male eat....."); } } class Female extends Human{ public void eat() { System.out.println("Female eat......"); } }
转型注意事项:变量
package com.day04; /** * @author SFJ * @date 2019/11/10 * @time 22:17 **/ public class Test3 { public static void main(String[] args) { A a1 = new B();//向上转型 a1.methoda();//调用父类方法,没有B类的方法,至关于父类对象 B b1 = (B)a1;//向下转型,前提已经向上转型 b1.methoda();//调用父类A方法 b1.methodB();//调用B类方法 b1.methodNew(); A a2 = new A(); B b2 = (B) a2; // 向下转型,编译无错误,运行时将出错 b2.methoda(); b2.methodB(); b2.methodNew(); } } class A { void methoda() { System.out.println("A method"); } } class B extends A{ void methodB() { System.out.println("B method"); } void methodNew() { System.out.println("BNew method"); } }