本文主要是介绍Java学习第十八节之instanceof和类型转换,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
instanceof和类型转换
instanceof
//Object > String//Object Person>Teacher//Object Person>StudentObject object = new Student();//System.out.println(X instanceof Y);//能不能编译通过!System.out.println(object instanceof Student);//trueSystem.out.println(object instanceof Person);//trueSystem.out.println(object instanceof Object);//trueSystem.out.println(object instanceof Teacher);//falseSystem.out.println(object instanceof String);//falseSystem.out.println("=================================");Person person = new Student();System.out.println(person instanceof Student);//trueSystem.out.println(person instanceof Person);//trueSystem.out.println(person instanceof Object);//trueSystem.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);//trueSystem.out.println(student instanceof Person);//trueSystem.out.println(student instanceof Object);//true//System.out.println(student instanceof Teacher);//编译报错!//System.out.println(student instanceof String);//编译报错!
类型转换
package oop;import oop.demo06.Person;
import oop.demo06.Student;
import oop.demo06.Teacher;//一个项目应该只存一个main方法
public class Application {public static void main(String[] args) {//类型之间的转化:父 子//子类转换为父类,可能丢失自己的本来的一些方法Student student = new Student();student.go();Person person = student;}
}/*
1.父类引用指向子类的对象
2.把子类转换为父类,向上转型:
3.把父类转换为子类,向下转型:强制转换
4.方便方法的调用,减少重复的代码!简洁封装,继承,多态! 抽象类,接口*/
这篇关于Java学习第十八节之instanceof和类型转换的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!