Java 向上转型和向下转型
程序中存在继承关系的类,
向上转型来使用父类中独有的方法,
向下转型来使用子类中独有的方法。
1、定义测试类
定义People父类,类中写hh()和haha()两个方法
class People{
public void hh(){
System.out.println("People hh");
}
public void haha(){
System.out.println("People haha");
}
}
定义Student子类继承People,重写父类的hh()方法,并创建一个新的xixi()方法
class Student extends People{
@Override
public void hh(){
System.out.println("Student hh");
}
public void xixi(){
System.out.println("Student xixi");
}
}
2、向上转型
public class Demo4 {
public static void main(String[] args) {
//实例化一个Student的对象,并使用People的引用来指向它,此时就实现了一个向上转型,
//父类引用指向子类对象,也是java多态性的一种体现
People p1=new Student();
p1.hh();
p1.haha();
}
}
运行结果:
3、向下转型
public class Demo4 {
public static void main(String[] args) {
//向下转型,为了使用子类独有的方法
People p1=new Student();
Student s1=(Student) p1;
s1.xixi();
s1.hh();
s1.haha();
}
}
运行结果:
4、常见错误转型
在向上和向转型中,实际上只创建了一个Student的对象,转型只是在对象的引用上,程序中的p1和s1只是对象的一个引用。
常见的错误转型,会错误的将子类的引用指向父类对象,这并不是向下转型,编译阶段会报出java.lang.ClassCastException的类型转换异常
代码如下:
public static void main(String[] args) {
People p1=new People();
Student s1=(Student) p1;//编译阶段报错,类型转换异常