向上转型和向下转型的区别

关于多态:

来看一个案例:

1.向上转型

package com.kxy.poly;

class Animal{
	 String name="动物";
	 public void sleep() {
		 System.out.println("睡");
	 }
	 public void run() {
		 System.out.println("跑");
	 }
	 public void eat() {
		 System.out.println("吃");
	 }
}
class Cat extends Animal{
	public void eat() {
		System.out.println("猫吃鱼");
	}
	public void catchMouse() {
		System.out.println("猫抓老鼠");
	}
}
class Dog extends Animal{
	public void eat() {
		System.out.println("狗吃骨头");
	}
	public void cry() {
		System.out.println("汪汪汪!~");
	}
}
public class poly01 {
	public static void main(String[] args) {
		Animal animal=new Cat();//向上转型
		animal.eat();
//		animal.catchMouse();//向上转型实例化的对象不能访问子类特有成员
		animal =new Dog();//animal的地址更改为指向dog类
		animal.eat();
//		animal.cry();//同样不能访问狗的特有成员		
	}
}

这就是向上转型,精通向上转型你只需要掌握下面几个知识点:

1.本质:父类的引用指向了子类的对象

2.语法:父类 引用名 =new 子类();

3.特点(非常重要)编译类型看左边,运行类型看右边。

可以调用父类中原有的所有成员(需遵守访问权限)但不能调用子类中特有成员。

2.向下转型

package com.kxy.poly;

class Animal{
	 String name="动物";
	 public void sleep() {
		 System.out.println("睡");
	 }
	 public void run() {
		 System.out.println("跑");
	 }
	 public void eat() {
		 System.out.println("吃");
	 }
}
class Cat extends Animal{
	public void eat() {
		System.out.println("猫吃鱼");
	}
	public void catchMouse() {
		System.out.println("猫抓老鼠");
	}
}
class Dog extends Animal{
	public void eat() {
		System.out.println("狗吃骨头");
	}
	public void cry() {
		System.out.println("汪汪汪!~");
	}
}
public class poly01 {
	public static void main(String[] args) {
		Animal animal=new Cat();//向上转型
		animal.eat();
//		animal.catchMouse();//向上转型实例化的对象不能访问子类特有成员
		
		Cat cat=(Cat) animal;
		cat.eat();
		cat.catchMouse();//向下转型可以访问特有属性和方法
		//Dog dog= (Dog) animal;//此时animal不再是父类,不能用子类Dog强制转换子类Cat
		//dog.cry();
	}
}

1.语法:子类 引用名 =(子类)父类引用;

2.只能强制转换父类的引用,不能是父类

3.要求父类的引用必须指向的是当前目标类型的对象,就本案例来讲,就是animal必须指向Cat类

4.可以调用子类中所有成员。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

❀༊烟花易冷ღ

觉得博客写的不错就打赏一下吧

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值