instanceof关键字 和类型转换
instanceof:
作用:
* 用来判断两个类是否具有父子关系,如果有父子关系,则会返回true。
* 为了避免在向下转型中出现classcastException的异常,在向下转型之前先使用instanceof进行判断。
* 如果a instanceof A 返回true,则a instacneof B也返回true,其中B是A的父类
代码示例:
Person.java
public class Person {
public void run() {
System.out.println("run");
};
}
Student.java
public class Student extends Person{
@Override
public void run() {
System.out.println("sun");
}
public void eat() {
System.out.println("ear");
}
public void go() {
System.out.println("go");
}
}
Teacher.java
public class Teacher extends Person{
}
测试类:app.java
public class app {
public static void main(String[] args) {
//Object > String
//Object > Person > Teacher
//Object > Person > Student
Object object=new Student();//代表当前这个object对象是Student的对象
//System.out.println(X instanceof Y);//能不能编译通过的原则X Y之间是否具有父子关系,
System.out.println(object instanceof Student);//true
System.out.println(object instanceof Person);//true
System.out.println(object instanceof Object);//true
System.out.println(object instanceof Teacher);//false
System.out.println(object instanceof String);//false
//其中Object和String是有关系的,Object和Student也有关系,但是Student和String没有父子关系,所以会返回False
System.out.println("=================");
Person person = new Student();
//生成了一个Student类型的对象,但是最高级是Person,Person和String没有关系,所以会报错
System.out.println(person instanceof Student);//true
System.out.println(person instanceof Person);//true
System.out.println(person instanceof Object);//true
System.out.println(person instanceof Teacher);//false
//System.out.println(person instanceof String); //两个类没有一点关系,所以会导致编译报错
System.out.println("=================");
Student student = new Student();
System.out.println(student instanceof Student);//true
System.out.println(student instanceof Person);//true
System.out.println(student instanceof Object);//true
//System.out.println(student instanceof Teacher);//Student和Teacher两个类没有一点关系,所以会导致编译报错
//System.out.println(person instanceof String); //Student和String两个类没有一点关系,所以会导致编译报错
}
}
类型转换:
作用:方便方法的调用,减少重复的代码
-
父类引用指向子类对象。
-
把子类转换为父类则会进行向上转型;不需要强制类型转换。
-
把父类转换为子类为向下转型;需要进行强制类型转换。
代码示例:
-
public class app { public static void main(String[] args) { //类型转化:其中包括父子关系转化h //还有高低之间的转化---->低转高不需要进行强制类型转换,高转低需要进行强制类型转换 Person obj=new Student(); //student将这个对象转换为Students类型,就可以直接使用student类型的方法了 Student student=(Student)obj; student.go(); //((Student)obj).go();两种方法都可以进行强制转换 //子类转换到父类,可能会丢失自己本来的一些方法 Person person=student; } }
-