instanceof与类型的转换
-
判断一个对象是什么类型
-
instanceof通常用来判断两个类或方法之间是否有联系
package com.yuecheng.oop;
import com.yuecheng.oop.Demo06.Student;
import com.yuecheng.oop.Demo06.Person;
import com.yuecheng.oop.Demo06.Teacher;
public class Application {
public static void main(String[] args) {
// Object>Person>Student
//Obgect>String
//instanceof 左右类或者对象间有练习就会返回true;否则返回flase
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 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
// 这里Person是和Teacher有关系的,但是通过Student new出的person对象和Teacher无关的
//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 String);编译就会报错
//System.out.println(student instanceof Teacher);编译就会报错,
//因为这里的学生和老师并没有直接的联系,只是都继承了Person这个父类罢了。
}
}
类型的转换
- 父—>子(高转低,需要强制转换)
- 因为 父类想要使用子类独有的方法,所以为了实现这个功能,就把父类伪装成子类即可。
package com.yuecheng.oop;
import com.yuecheng.oop.Demo06.Student;
import com.yuecheng.oop.Demo06.Person;
import com.yuecheng.oop.Demo06.Teacher;
public class Application {
public static void main(String[] args) {
Student student = new Student();
//student.go();
Person S1 = new Student();
//S1.go();会报错,不能使用,因为高类不能调用低类的方法,所以要进行类型的转换
//((Student)S1).go();//对S1进行强制转换为Student类型,可以使用GO
//或者
Student s1 = (Student) S1;
s1.go();//转换完成 可以使用
}
}
- 子---->父(低转高自动转化)
package com.yuecheng.oop.Demo06;
public class Teacher extends Person{
//类型的转换:子 -- 父
public static void main(String[] args) {
Student student = new Student();
Person s2 = student;//自动转换
//s2.go(); 子类转化为父类,丢失子类的go()方法!
//所以要注意,子类转父类可能会丢失一些方法!
}
}
注意
- 父类引用可以指向子类对象
- 把子类转为父类,向上转型,直接转,但会丢失子类一些独有的方法,
- 父转子:向下转型,需要强制转型,丢失父类被子类所重写掉的方法!
- 方便方法的调用,减少重复代码!
- 抽象:封装!继承!多态!
- 抽象的编程思想:需要持续学习:茅塞顿开!多实践!多测试大脑中的想法