三大特性之多态

1、多态:对象的多种形态。有引用多态、方法多态。

(1)引用多态:

父类的引用可以指向本类的对象。

父类的引用可以指向子类的对象。

但是子类的引用是不能指向父类的。比如Dog dog=new Animal();//编译报错Type mismatch: cannot convert from Animal to Dog。

package com.imooc;
 public class Animal {
	 Animal obj1=new Animal();
	 Animal obj2=new Dog();//父类的引用可以指向子类,称为引用多态	 
}
(2)方法多态:

创建本类对象时,调用的方法是本类的方法。

创建子类对象时,调用的方法为子类重写的方法或者继承的方法。

package com.imooc;
public class Initial {
	public static void main(String[] args) {
		Animal obj1=new Animal();
		Animal obj2=new Dog();
		obj1.eat();
		obj2.eat();
	}
}
package com.imooc;
 public class Animal {
	 public void eat(){
		 System.out.println("动物具有吃的能力");
	 } 
}
package com.imooc;
public class Dog extends Animal {
	public void eat(){
		System.out.println("狗是吃肉的。");
	}	
}
执行结果:

动物具有吃的能力。(父类的方法)
狗是吃肉的。(子类的方法)
2、引用类型的转换

向上类型转换(也称隐式/自动类型转换),是小类型到大类型的转换。例如把杯子里的水倒进水壶里,是没有风险的。

向下类型转换(也称强制类型转换),是大类型到小类型的转换。例如将水壶的水倒进水杯里,是有风险的。

但是instanceof运算符,可以避免类型转换的安全性问题。

package com.imooc;
public class Initial {
	public static void main(String[] args) {
		 Dog dog=new Dog();
		 Animal animal=dog;// 自动类型提升,向上类型转换
		 Dog dog2=(Dog)animal;//向下类型转换,强制类型转换
		 Cat cat=(Cat)animal;//编译时Cat类型;运行时Dog类型,就会发生类型不匹配。
	}
}
Dog和Cat都是Animal的子类,但是 Cat cat=(Cat)animal;会报错:(Dog无法转换成Cat)

Exception in thread "main" java.lang.ClassCastException: com.imooc.Dog cannot be cast to com.imooc.Cat
at com.imooc.Initial.main(Initial.java:7)
通过instanceof运算符能够判断一个引用是否是某个类型或者某个类型的子类型,返回布尔值。

package com.imooc;
public class Initial {
	public static void main(String[] args) {
		 Dog dog=new Dog();
		 Animal animal=dog;// 自动类型提升,向上类型转换
		 Dog dog2=(Dog)animal;//向下类型转换,强制类型转换
		 if(animal instanceof Cat){
			 Cat cat=(Cat)animal;
		 }else{
			 System.out.println("无法进行类型转换。");
		 }
		 
	}
}
运行结果:无法进行类型转换。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值