您的位置:首页 > 其它

多态使用中对象是向上转型或是向下转型的区别

2016-09-24 20:23 399 查看
多态基于继承;主要表现是重写; - -其实表现方式是重写和重载

对于创建的对象是向上转型还是向下转型:
向上转型:只能调用与父类引用中父类相同的方法,不能调用子类中自己定义的方法;如果在子类中重写了,则调用的是子类中的方法;

向下转型:可以调用父类中的方法,也可以调用子类中自己定义的方法;如果子类中重写了父类的方法,调用的是子类中重写的方法;

/**
* 测试类:验证多态中向上转型和向下转型的区别
* @author
*
*/
public class Demo{
public static void main(String []args){
Parent p = new Child(); //向上转型
p.eat();
p.sleep(); //调用的子类中重写父类的方法
//p.play();//错误,此时调用不了子类重载的方法

Child d = (Child) p; //向下转型
d.sleep(); //调用的子类中重写父类的方法
d.sleep("hi"); //子类中可以重载父类方法
d.play(); //可以调用子类自己定义的方法

}
}
/**
* 子类继承父类
* @author
*
*/
class Child extends Parent
{

//重载父类方法
public void sleep(String str){
System.out.println(str+",child sleep");
}
//重写父类中的方法
public void sleep(){
System.out.println("child sleep");

}
//子类中自己定义的方法
public void play(){
System.out.println("child play");
}

}

/**
* 父类
* @author
*
*/
class Parent{
public void sleep(){
System.out.println("Parent sleep");
}
public void eat(){
System.out.println("Parent eat");
}
}

输出结果为:
Parent eat
child sleep
child sleep
hi,child sleep
child play
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息