instanceof与类型转换
package com.andy.base.oop.demo01.demo06;
public class Teacher extends Person {
}
package com.andy.base.oop.demo01.demo06;
public class Student extends Person {
public void go(){
System.out.println("go");
}
}
/*
//Object > String
//Object > Person >Teacher
//Object > Person >Student
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(person instanceof String);// 编译错误
*/
package com.andy.base.oop.demo01.demo06;
public class Person {
public void run(){
System.out.println("run");
}
}
main
package com.andy.base.oop.demo01;
import com.andy.base.oop.demo01.demo06.Person;
import com.andy.base.oop.demo01.demo06.Student;
public class Application {
public static void main(String[] args) {
//基本类型转换: 父(高) 子(低)
//高 低
Person student = new Student();
// student.go(); //student调用的是 Person ,Person类中没有go方法
//student 将这个对象转换为Student类型,我们就可以使用Student类型的方法了!
((Student)student).go();
Student student1 = new Student();
student1.go();
Person person = student; //低 --->高 (自动)Student --->Person
}
}
/*
1.父类引用指向子类的对象
2.把子类转换为父类,向上转型;
3.把父类转换为子类,向下转型;强制转换
4.放便方法的调用,减少重复的代码!简介
封装、继承 、多态 抽象类,接口
*/
标签:instanceof,类型转换,System,Person,Student,println,out
From: https://www.cnblogs.com/zhongjianYuan/p/17162412.html