1.Instanceof作用 用來判斷兩個兩個類之間是否存在父子關係 代碼及詳解如下: Application類代碼 點擊查看代碼 package com.Tang.oop.demo06; public class Application { public static void main(Stri ...
1.Instanceof作用
用來判斷兩個兩個類之間是否存在父子關係 代碼及詳解如下: Application類代碼點擊查看代碼
package com.Tang.oop.demo06;
public class Application {
public static void main(String[] args) {
//Object > String
//Object > Person > Student
//Object > Person > Teacher
Object object = new Student();
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);//false
// 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);//編譯報錯
/*
總結:看編譯能否通過主要是看對象左邊的類型與instanceof 右邊的類是否有父子關係
看運行結果為true或false主要是看對象所指向的引用(右邊的類)與instanceof右邊的類是否存在父子關係
*/
}
}
2.強制轉換
Application類代碼
點擊查看代碼
package com.Tang.oop.demo06;
public class Application {
public static void main(String[] args) {
Person person = new Student();
//Person相較於Student類是比較高的類,由高到低需要強制轉換
//也就是將person對象強制轉化為Student類,才能調用go方法
((Student)person).go();
Student student = new Student();
student.go();
//由低向高轉則不需要強轉,但是轉化為高之後可能就會丟失一些方法
Person person1 = student;
// person1.go();
}
}
點擊查看代碼
package com.Tang.oop.demo06;
public class Student extends Person{
public void go(){
System.out.println("go");
}
}
點擊查看代碼
package com.Tang.oop.demo06;
public class Person {
public void run(){
System.out.println("run");
}
}