向下转型 java特性_JAVA:向下转型和instanceof运算符的应用

知识梳理

一:向下转型

1.向下转型:向下转型是与向上转型相对的概念,他是用子类引用指向父类实例.

如:

Animal animal = new Dog();

Dog d = animal;// 报错

这时就告诉我们向下转型不能自动转换,我们需要强转,所以向下转型又叫做强制类型转换.

正确的转换语句为:

Animal animal = new Dog();

Dog dog = (Dog)animal;

2.向下转型后,可以调用子类自己独有的方法.

public class Animal{

String name;

int age;

public Animal(){

}

public void eat(){

System.out.println("animal吃东西");

}

public static void die(){

System.out.println("animal死亡");

}

}

public class Dog extends Animal{

String favoriteFood;

public void eat(){

System.out.println("吃肉");

}

public void run(){

System.out.println("夕阳下奔跑的小狗");

}

public static void die(){

System.out.println("dog死亡");

}

}

public static void main(String[] args){

Animal animal = new Dog(); // 向上转型

Dog dog = (Dog)animal; // 强制类型转换

dog.run(); // 调用子类独有的方法

}

3.兄弟类之间不能进行强制类型转换.

public class Cat extends Animal{

}

public static void main(String[] args){

Animal animal = new Cat(); // 向上转型

Dog dog = (Dog)animal; // 编译时不报错误,运行时会包错误:

}

错误如下:

b633097bb545

1.png

二:instanceof运算符

1.基本概念

instanceof 运算符用来判断对象是否可满足某个特定类型实例特征.返回值为true/false.一般用于if语句中

表示方法为:

b633097bb545

2.png

boolean result;

Animal animal = new Dog();

result = animal instanceof Dog; // result 结果为true

// 如果左边对象是右边类的实例则返回true,否则返回false

2.instanceof运算符的应用

1)用instanceof运算符来判断对象是否可满足某个特定类型实例特征

// 例子:父类Parents类、Father类和Mother类分别为它的两个子类:

// 实例化对象

Parents father = new Father();

Parents mother = new Mother();

// 用instanceof运算符判断对象是否满足某个特定对象实例特征

System.out.println(mother instanceof Father);

System.out.println(mother instanceof Mother);

System.out.println(mother instanceof Object);

System.out.println(father instanceof Father);

输出结果为:

false

true

true

true

注:java中所有类都直接或间接继承于Object类.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值