类的实例包含本身的实例,以及所有直接或间接子类的实例
instanceof左边显式声明的类型与右边操作元必须是同种类或存在继承关系,也就是说需要位于同一个继承树,否则会编译错误
在编译状态中,class可以是object对象的父类,自身类,子类。在这三种情况下Java编译时不会报错。
在运行转态中,class可以是object对象的父类,自身类,不能是子类。在前两种情况下result的结果为true,最后一种为false。但是class为子类时编译不会报错。运行结果为false。
public class Person {
public void test(){
System.out.println("父类方法");
}
}
public class Teacher extends Person{
}
public class Student extends Person{
}
public class Application {
public static void main(String[] args) {
//Object > Person > Student
//Object > Person > Teacher
//Object > String
Object obj = new Student();
System.out.println(obj instanceof Student);
System.out.println(obj instanceof Teacher);
System.out.println(obj instanceof Object);
System.out.println(obj instanceof Person);
System.out.println(obj instanceof String);
System.out.println("============================");
Person person = new Student();
System.out.println(person instanceof Student);
System.out.println(person instanceof Teacher);
System.out.println(person instanceof Object);
System.out.println(person instanceof Person);
System.out.println("============================");
Person person1 = new Person();
System.out.println(person1 instanceof Student);
System.out.println(person1 instanceof Teacher);
System.out.println(person1 instanceof Object);
System.out.println(person1 instanceof Person);
}
}
//
true
false
true
true
false
============================
true
false
true
true
============================
false
false
true
true
public class Person {
public void test(){
System.out.println("父类方法");
}
}
public class Student extends Person{
public void study(){
System.out.println("students is studying!");
}
}
public class Application {
public static void main(String[] args) {
//类型转化 父-子
Person person = new Student();
//person.study(); 不能执行子类方法
// 将Person 转化为 student,就可以使用student的方法
((Student) person).study();
}
}
//students is studying!
//子类转化为父类,会丢失子类的方法
Student student = new Student();
student.study();
Person per = student;
//per.study();
/*
1.父类引用指向子类的对象
2.把子类转化为父类,向上转型
3.把父类转化为子类,向下转型
4.方便方法的调用,减少重复代码。
*/
原文:https://www.cnblogs.com/saxonsong/p/14628726.html