instanceof和类型转换
instanceof和类型转换
instanceof判断具体实例与类对象的关系
package Demo01;public class Person {}
package Demo01;public class Student extends Person{}
package Demo01;public class Application {public static void main(String[] args) {//Object->String//Object->Person->StudentObject 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 String);System.out.println( );Student student1 = new Student();System.out.println(student1 instanceof Student);System.out.println(student1 instanceof Person);System.out.println(student1 instanceof Object);//System.out.println(student1 instanceof String);System.out.println( );Person student2 = new Student();System.out.println(student2 instanceof Student);System.out.println(student2 instanceof Person);System.out.println(student2 instanceof Object);//System.out.println(student2 instanceof String);//System.out.println(x instanceof Y);判断x和Y有没有继承关系//具体实例与实际类型的父子类的instanceof为true//具体实例与引用类型的父子类的instanceof为false}
}
输出结果为:
true
true
true
false
true
true
true
true
true
true
类型转换
- 父类引用指向子类的对象
- 把子类转换为父类,向上转型
- 把父类转换为子类,向下转型;强制转换
- 方便方法的调用,减少代码的重复性,更简洁。
package Demo01;public class Person {}
package Demo01;public class Student extends Person{
public void test(){System.out.println("测试");
}}
package Demo01;public class Application {public static void main(String[] args) {//Student为Object的子类 由低转高Object a = new Student();//a.test()无法使用Student的方法因为不是Student类型//将a对象转换成Student类型,使用其方法Student a1 = (Student) a;a1.test();Student student1 = new Student();Person person=student1;//person.test();//子类转成父类,会丢失原本自己子类的方法}
}
输出结果为:
测试