全网最细之instanceof和类型转换
生活随笔
收集整理的這篇文章主要介紹了
全网最细之instanceof和类型转换
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
package com.wuming.oop4.demo08;public class Application {public static void main(String[] args) {//類型之間轉換:父 子//高 低Person person1 = new Student();//student將這個對象轉換為student類型,我們就可以使用student類型的方法了!Student student = (Student) person1;student.go();//go((Student) person1).go();//go//從右往左看Person person=student;//子類轉父類Student student1= (Student) person1;// 父轉子,強制}
}
/*
1.父類引用指向子類對象
2.子類轉換為父類,向上轉型
3.父轉子,強制
4.方便方法的調用,減少重復的代碼
*/
package com.wuming.oop4.demo08;public class Person {}
package com.wuming.oop4.demo08;public class Student extends Person {public void go() {System.out.println("go");}//Application.java里面的拿過來的
// //Object>String
// //Object>Person>Teacher
// //Object>Person>Student 三行中同級間(列對應)instance of指向會報錯
// Object object = new Student();
// //System.out.println(x instanceof y);//能不能編譯通過,就看x和y有沒有父子關系
// System.out.println(object instanceof Student);//true
// System.out.println(object instanceof Person);//true
// System.out.println(object instanceof Object);//true
// 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);//true
// System.out.println(person instanceof Person);//true
// System.out.println(person instanceof Object);//true
// // 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);//true
// System.out.println(student instanceof Person);//true
// System.out.println(student instanceof Object);//true
// // System.out.println(student instanceof Teacher);
// // System.out.println(student instanceof String);
}
go
go
?
總結
以上是生活随笔為你收集整理的全网最细之instanceof和类型转换的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python中文编码 - Python零
- 下一篇: Python set list dict