转型是在继承的基础上而言的,继承是面向对象语言中,代码复用的一种机制,通过继承,子类可以复用父类的功能,如果父类不能满足当前子类的需求,则子类可以重写父类中的方法来加以扩展。
向上转型:子类引用的对象转换为父类类型称为向上转型。通俗地说就是是将子类对象转为父类对象。此处父类对象可以是接口
向下转型:父类引用的对象转换为子类类型称为向下转型。
如以下案例
public class A {
public static void main(String[] args) {
Person person = new Son();//向上转型
person.name();//向上转型的方法只有name方法,找不到Age方法
// Son sonerror = (Son) new Person();//错误的向下转型,编译通过,运行报错
// sonerror.Age();
if(person instanceof Son)
{
Son son = (Son) person;//正确的向下转型
son.Age();
son.name();
}
}
}
class Person{
void name(){
System.out.println("this is Person name");
}
}
class Son extends Person{
@Override
void name() {
System.out.println("this is Son name");
}
void Age(){
System.out.println("this is Son age");
}
}
向上转型:子类引用的对象转换为父类类型称为向上转型。通俗地说就是是将子类对象转为父类对象。此处父类对象可以是接口
向下转型:父类引用的对象转换为子类类型称为向下转型。
如以下案例
public class A {
public static void main(String[] args) {
Person person = new Son();//向上转型
person.name();//向上转型的方法只有name方法,找不到Age方法
// Son sonerror = (Son) new Person();//错误的向下转型,编译通过,运行报错
// sonerror.Age();
if(person instanceof Son)
{
Son son = (Son) person;//正确的向下转型
son.Age();
son.name();
}
}
}
class Person{
void name(){
System.out.println("this is Person name");
}
}
class Son extends Person{
@Override
void name() {
System.out.println("this is Son name");
}
void Age(){
System.out.println("this is Son age");
}
}