前言
上一篇我们共同学习了类的多态性,对于类的封装、继承、多态的大概知识我们已经学习完了,之后我们将一起学习一下一些小的知识点,今天我们先学习instanceof方法和类的类型转化。
一、instanceof方法和类的类型转换
- instanceof方法:
instanceof方法用于检测两个类之间,以及类与对象之间是否有关系,如果有关系则为 true或者false,没有关系则程序报错不能执行。 - 类的类型转换: 如果指向子类的父类对象想要调用子类的特有的方法则需要进行类型转换,将父类对象强制转换为子类对象,如果是子类转换为父类则不需要强制转换,但子类可能会丢失一些自己的方法。
二、代码示例
1.instanceof方法
代码如下(示例):
1.Person类(父)
public class Person {
public void run(){
System.out.println("P_run");
}
}
2.Student类(子)
public class Student extends Person{
public void go(){
System.out.println("S_go");
}
}
3.Teacher类(子)
public class Teacher extends Person{
}
3.Application类(测试类)
public class Application {
public static void main(String[] args){
//Object > Person > Student
//Object > Person > Teacher
//Object > String
//System.out.println("X instanceof Y");//X与Y有关系时不报错!
Object object = new Student();
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
System.out.println("==============================");
Person person = new Student();
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);//编译报错
//System.out.println(student instanceof String);//编译报错
}
}
运行结果:
2.类的类型转换
代码如下(示例):
1.Person类(父)
public class Person {
public void run(){
System.out.println("P_run");
}
}
2.Student类(子)
public class Student extends Person{
public void go(){
System.out.println("S_go");
}
}
3.Application类(测试类)
public class Application {
public static void main(String[] args){
//类型之间的转换:父(高) -> 子(低),需要强制转换;
//double a1 = 0; int b1 = (int)a1;
Person obj = new Student();
//将obj由Person(父类)类型转换为Student(子类)类型,就可以使用子类的方法了
Student student = (Student) obj;
((Student)obj).go();
student.go();
student.run();
//类型之间的转换:子(低) -> 父(高),不需要强制转换;
// int a2 = 0; double b2 = a2;
Student obj1 = new Student();
//将obj由Student(子类)类型转换为Person(父类)类型,可能丢失自己一些本来的方法
Person person = obj1;
person.run();
}
}
运行结果:
总结
- 当用new创建类与对象A a = new X() 时,X为你选定的类;
使用instanceof关键词(a instanceof Y)Y为任意的类:- 当a,Y有关系且在A->X的路径上时结果为true;
- 当a,Y有关系但不在A->X的路径上时结果为flase;
- 当a,Y没有关系且不在A->X的路径上时程序出错;
- 类的类型转换:
- 父类引用指向子类的对象;
- 把子类转换为父类:子(低)-> 父(高),不用强制转换;
- 把父类转换为子类:父(高)-> 子(低),需要强制转换;
- 方便方法的调用,减少重复代码!