Application类
//Object>String
//Object>Person>Student
//Object>Person>Teacher
Object object = new Student();
System.out.println(object instanceof Student);//1
System.out.println(object instanceof Person);//1
System.out.println(object instanceof Object);//1
System.out.println(object instanceof Teacher);//0
System.out.println(object instanceof String);//0
输出:
true
true
true
false
false
说明了:
Object>String
Object>Person>Student
Object>Person>Teacher
System.out.println(X instanceof Y);
看X跟Y是否有父子关系
Student类:写了一个go方法
package com.oop.demo03;
public class Student extends Person {
public void go(){
System.out.println("gogogo");
}
}
Person类:写了一个run方法
package com.oop.demo03;
public class Person {
public void run(){
System.out.println("runrunrun");
}
}
Application类:父类对象使用子类方法怎么办??:实现高转低
package com.oop.demo03;
public class Application {
public static void main(String[] args) {
//高 低
Person s = new Student();
//将Person类的s这个对象转化为Student类型,就可以使用Student类型的方法了
//高转低怎么转?:强制转换
//1. ()s
//2. (Student)s;
Student s1 = (Student) s;
//怎么使用方法?: 对象名.方法名(); 谁要干什么事;
s1.go();
}
}
输出:gogogo
简写变成一句话就是:
((Student)s1).go;
- 父类引用指向子类的对象
- 子类转父类,向上转型
- 父类转子类,向下转型,需要强制转换
- 方便方法的调用,减少重复的代码