X instanceof Y:判断X和Y是否存在父子关系
X:对象,Y:类,如果X对象是Y类(或者其子类)的实例,输出true,否则输出false。
若X和Y之间不存在关系,则编译不通过。
也可以说,编译看左边,运行看右边!
例如:
package com.oop;
import com.oop.Test06.Person;
import com.oop.Test06.Student;
import com.oop.Test06.Teacher;
public class Application {
public static void main(String[] args) {
//Object>String
//Object>Person>Teacher
//Object>Person>Student
//System.out.println(X instanceof Y);
//能不能编译通过,X和Y之间是否存在父子关系,若没有关系,则编译就不通过。
Object object = new Student();
System.out.println(object instanceof Student);
System.out.println(object instanceof Person);
System.out.println(object instanceof Object);
System.out.println(object instanceof Teacher);//同一级,二者有关系,但不是父子关系,所以结果返回false。
System.out.println(object instanceof String);//二者有关系,但不是父子关系,所以结果返回false。
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);//同一级,二者有关系,但不是父子关系,所以结果返回false。
//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(student instanceof String);//不存在关系,编译报错!
}
}
输出:
true
true
true
false
false
========================================
true
true
true
false
========================================
true
true
true
类型转换:
我们之前的基本类型转换:低到高,满足自动转换,高到低则需要强制转换。
多态中的类型转换:父类:高,子类:低。同样满足高到低,强制转换,低转高自动转。
在编写Java程序时,引用变量只能调用它编译时类型的方法,而不能调用它运行时类型的方法,如果想要让这个引用变量来调用它运行时类型的方法,必须使用强制类型转换把它转换成运行时类型。
向下类型转换:
语法格式:
(( 目标子类类型)当前待转换的对象名).子类方法()
例如:
((Student) obj).go();
package com.oop;
import com.oop.Test06.Person;
import com.oop.Test06.Student;
public class Application {
public static void main(String[] args) {
//基本类型转换:高 低 64 32 高转低,就得强制转换。
//父子类型之间的转化:父到子,高->低,需要强制转换。
Person obj = new Student();
//将这个对象转换为Student类型,就可以使用Student类型的方法了。强转!!
Student student = (Student) obj;
student.go();
((Student) obj).go();//这句等同于上面那句等同于上面的那两句!
Person person = student;//低转高,可自动转换!
//person.go();编译报错,此时person是父类,无法执行子类的go方法。
//由此可以发现:子类转换为父类,可能会丢失一些自己本身的方法!
}
}
//子类:Student类:
package com.oop.Test06;
public class Student extends Person{
public void go(){
System.out.println("go");
}
}
//子类:Teacher类
package com.oop.Test06;
public class Teacher extends Person{
}
//父类:Person类
package com.oop.Test06;
public class Person {
public void run(){
System.out.println("run");
}
}
输出:
go
go
多态总结:
1.父类引用指向子类的对象。
2.把子类转换为父类:向上转型,不用强转,但可能会丢失一些方法
3.把父类转换为子类:向下转型,强转,重写失效。
4.方便方法的调用,减少重复的代码。
视频学习,来源于B站狂神说Java,欢迎小伙伴们学习~