instanceof:
- 比较转换,要有父子关系才会返回ture或者false
父类
public class Person {
}
子类Student
public class Student extends Person{
public void go(){
System.out.println("go");
}
}
子类Teacher
public class Teacher extends Person{
}
比较转换
//instanceof:会比较转换,要有父子关系才会返回ture或者false
public class Application {
public static void main(String[] args) {
//Object>String
//Object>Person>Student
//Object>Person>Teacher
Object object = new Student();
//System.out.println(x instanceof y);//代码编译能否通过,看x和y是否有父子继承关系
//判断类型是否相似
System.out.println(object instanceof Student);//Ture
System.out.println(object instanceof Person);//Ture
System.out.println(object instanceof Object);//Ture
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);//Ture
System.out.println(person instanceof Person);//Ture
System.out.println(person instanceof Object);//Ture
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);//Ture
System.out.println(student instanceof Person);//Ture
System.out.println(student instanceof Object);//Ture
//System.out.println(student instanceof Teacher);//False
//System.out.println(student instanceof String);//False
//注意:比较转换,要有父子关系才会返回ture或者false
}
}
强制类型转换
Person obj = new Student();
//student将Person父类转换成子类Student类型,就可以用子类的方法
//表示1
Student student = (Student)obj;
student.go();
//表示2
((Student)obj).go();
//子类转换成父类会丢失子类独有的方法和重写方法
Student student2 = new Student();
student2.go();
Person person = student2;
//person.go();
//(类名)实例
public class Application2 {
public static void main(String[] args) {
//类型之间的转换:前面学过64位类型转成32位列如:double型转int需要强制转换
//这里父类代表高的,子类代表低的,高转低要强制
Person obj = new Student();
//student将Person父类转换成子类Student类型,就可以用子类的方法
//表示1
Student student = (Student)obj;
student.go();
//表示2
((Student)obj).go();
//子类转换成父类会丢失子类独有的方法和重写方法
Student student2 = new Student();
student2.go();
Person person = student2;
//person.go();
}
}
小结
- 父类引用指向子类的对象
- 把子类转换为父类,向上转换
- 父类转换成子类,向下转换:强制转换 (父类)子类
- 方便方法的调用,减少重复的代码!简洁思维
- 封装,继承,多态! 抽象类和接口