多态使用中对象是向上转型或是向下转型的区别
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
对于创建的对象是向上转型还是向下转型:
向上转型:只能调用与父类引用中父类相同的方法,不能调用子类中自己定义的方法;如果在子类中重写了,则调用的是子类中的方法;
向下转型:可以调用父类中的方法,也可以调用子类中自己定义的方法;如果子类中重写了父类的方法,调用的是子类中重写的方法;
/**
* 测试类:验证多态中向上转型和向下转型的区别
* @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
相关文章推荐
- 多态的使用和向上向下转型
- 面向对象之多态【向上转型与向下转型】
- 继承父类的方法,父类方法的覆写。 向上转型后父类对象执行被覆写后的方法 向上转型后再向下转型 非多态强转? 多态的例子
- java多态使用、向上转型、向下转型
- 面向对象中的多态,对象的向上转型和向下转型
- 面向对象_多态中向上转型和向下转型
- 重新认识java(五) ---- 面向对象之多态(向上转型与向下转型)
- 接口的使用方法和向上转型对象的区别
- [gkk传智]static与多态及向下向上转型,及多态调用总结
- Java中多态以及向上转型和向下转型
- JAVA笔记-多态的意义(向上转型与向下转型)
- 多态之:向下转型和向上转型
- 2.25 Java基础总结 ①多态②向上向下转型③instanceof
- 从零开始学Java之多态 向上转型与向下转型
- [gkk传智]static与多态及向下向上转型,及多态调用总结
- java多态中的向上转型和向下转型
- java多态向上、向下转型问题
- JAVA_多态性演示a____自动向上转型、向下转型、检查对象是否为某个类型(instanceof)
- Java向上转型与向下转型(子类的对象赋给父类的)
- JavaSe基础(14)-- 对象的转型 向上转型 向下转型