09intanceof 和类型转换
public class Application {
public static void main(String[] args) {
//Object>String
//Object>Person>Teacher
//Object>Person>Student
Object object =new Student();
//System.out.println(x instanceof y);//编译是否通过,就看x和y是否存在继承关系!
System.out.println(object instanceof Student);
System.out.println(object instanceof Person);
System.out.println(object instanceof Object);
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 Object);
System.out.println(person instanceof Teacher);
//System.out.println(person instanceof String);编译报错!
System.out.println("========================");
Student 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 Teacher);编译报错!
//System.out.println(person instanceof String);编译报错!
}
}
运行结果:
true
true
true
false
false
========================
true
true
true
false
========================
true
true
true
类型转换:
1.父类引用指向子类的对象
2.把子类转换为父类,向上转型
3.把父类转换成子类,向下转型:强制转换
4.方便方法的调用,减少重复的代码!简介
public class Person {
public void run(){
}
}
public class Student extends Person{
public void go(){
System.out.println("go");
}
}
public class Application {
public static void main(String[] args) {
//类型之间的转换 基础类型转换:高转低(强转),低转高直接转换
//类型之间的转换:父 子
//子类型转换为父类,可能丢失自己本来的一些方法
//高 低
Person obj=new Student();
//student将这个对象转换为Student类型,我们就可以使用Student类型的方法了
Student student =(Student)obj;
student.go();
Student student1 =new Student();
student1.go();
Person person=student1;
}
}

浙公网安备 33010602011771号