instanceof
引用类型,判断一个对象是什么类型
package oop01.demo02;
public class Application02 {
public static void main(String[] args) {
//System.out.println(x instanceof Y);
/*
是否存在父子关系 是否是指向的类型
*/
//Object--String
//Object -- person02 -- Student01
//Object -- person02 -- Teacher
Object object = new Student01();
System.out.println(object instanceof Student01);
System.out.println(object instanceof Person02);
System.out.println(object instanceof Object);
System.out.println(object instanceof Teacher);
System.out.println(object instanceof String);
System.out.println("======================");
Person02 person = new Student01();
System.out.println(person instanceof Student01);
System.out.println(person instanceof Person02);
System.out.println(person instanceof Object);
System.out.println(person instanceof Teacher);
//System.out.println(person instanceof String);
System.out.println("======================");
Student01 student01 = new Student01();
System.out.println(student01 instanceof Student01);
System.out.println(student01 instanceof Person02);
System.out.println(student01 instanceof Object);
//System.out.println(student01 instanceof Teacher);
}
}
true
true
true
false //
false
======================
true
true
true
false
======================
true
true
true
Process finished with exit code 0
类型转换
把父类转换为子类,向下转型;强制转换
(Son(father)).go();
go方法是Son中具有而Father中不具有的
package oop01.demo02;
public class Person02 {
public void run() {
System.out.println("run");
}
}
package oop01.demo02;
public class Student01 extends Person02{
public void go(){
System.out.println("go");
}
}
package oop01.demo02;
public class Teacher extends Person02{
}
package oop01.demo02;
public class Application03 {
public static void main(String[] args) {
//高 低
Person02 obj = new Student01();
((Student01)obj).go();//父类 -- 子类 向下转型 强制转换
}
}
//方法的调用 减少重复的代码
把子类转换为父类,向上转型
可能丢失自己本来的一些方法。
Student01 student01 = new Student01();
student01.go();
Person02 person02 = student01;
person02.go();//无法执行