instanceof
引用类型,判断一个对象是什么类型
使用方法:
System.out.println(X instanceof Y);
代码理解:
public class Application {
public static void main(String[] args) {
//Obiect>String
//Obiect>Person>Teacher
//Obiect>Person>Student
Object object=new Student();
System.out.println(object instanceof Student);
System.out.println(object instanceof Person);
System.out.println(object instanceof Object);
System.out.println(object instanceof Teacher);
System.out.println(object instanceof String);
System.out.println("==========================");
Person person=new Student();
System.out.println(person instanceof Student);
System.out.println(person instanceof Person);
System.out.println(person instanceof Object);
System.out.println(person instanceof Teacher);
//System.out.println(person instanceof String);编译报错
System.out.println("=========================");
Student student=new Student();
System.out.println(student instanceof Student);
System.out.println(student instanceof Person);
System.out.println(student instanceof Object);
/*System.out.println(student instanceof Teacher);
System.out.println(student instanceof String);编译报错*/
}
}
其Person是Student与Teacher的父类
类型转换
父类的引用指向子类的对象
把子类转换为父类,向上转型
把父类转换为子类,向下转换:强制转换
方便方法调用,减少重复的代码
强制转换:
package com.oop.demo06;
public class Application {
public static void main(String[] args) {
//类型之间的转换
//子类转换为父类可能丢失自己本来的一些方法
Person obj=new Student();
//student将这个对象转换为Student类型,我们就可以使用Student类型的方法了
Student student=(Student)obj;
student.go();
}
}
package com.oop.demo06;
public class Student extends Person {
public void go(){
System.out.println("go");
}
}
也可以这样写
package com.oop.demo06;
public class Application {
public static void main(String[] args) {
//类型之间的转换
//子类转换为父类可能丢失自己本来的一些方法
Person obj=new Stu