instanceof和类型转换
- System.out.println(x instanceof y);能否编译通过,要看x和y是否存在父子关系
package com.oop.Demo06;
public class Application {
public static void main(String[] args) {
Object object = new Student();
System.out.println(object instanceof Student);
System.out.println(object instanceof Person);
System.out.println(object instanceof Person);
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 Person);
System.out.println(person instanceof Teacher);
Student student = new Student();
System.out.println("=============");
System.out.println(student instanceof Student);
System.out.println(student instanceof Person);
System.out.println(student instanceof Person);
}
}
- 1、父类引用指向子类对象
2、把子类转向父类,向上转型
3、把父类转向子类,向下转型 强制转换
4、方便方法的调用,减少代码的重复
封装 继承 多态! 抽象类 接口
package opp.Demo06;
public class Application {
public static void main(String[] args) {
Person obj= new Student();
((Student)obj).go();
Student student = new Student();
Person person = student;
student.go();
}
}
package opp.Demo06;
public class Student extends Person{
public void go(){
System.out.println("go");
}
public void run(){
System.out.println("run");
}
}
package opp.Demo06;
public class Person {
public void eat(){
System.out.println("eat");
}
public void run() {
}
}