知识梳理
一:向下转型
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; // 编译时不报错误,运行时会包错误:
}
错误如下:
![](https://img.haomeiwen.com/i1502564/8a25da2d37af1be5.png)
二:instanceof运算符
1.基本概念
instanceof 运算符用来判断对象是否可满足某个特定类型实例特征.返回值为true/false.一般用于if语句中
表示方法为:
![](https://img.haomeiwen.com/i1502564/1ab30324e3aeb541.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类.
网友评论