标签:import 小结 转换 main wrap === code 向下转型 是什么
1 package com.oop.demo07; 2 3 public class Person { 4 5 public void run(){ 6 System.out.println("run"); 7 } 8 9 }
1 package com.oop.demo07; 2 3 public class Student extends Person { 4 5 public void go() { 6 System.out.println("go"); 7 } 8 9 }
1 package com.oop.demo07; 2 3 public class Teacher extends Person{ 4 }
1 package com.oop; 2 3 import com.oop.demo07.Person; 4 import com.oop.demo07.Student; 5 import com.oop.demo07.Teacher; 6 public class Application { 7 8 public static void main(String[] args) { 9 10 //Object > String 11 //Object > Person > Teacher 12 //Object > Person > Student 13 Object object = new Student(); 14 15 //System.out.println(X instanceof Y);//能不能编译通过!取决于X和Y之间是否存在父子关系! 16 System.out.println(object instanceof Student);//true 17 System.out.println(object instanceof Person);//true 18 System.out.println(object instanceof Object);//true 19 System.out.println(object instanceof Teacher);//False 20 System.out.println(object instanceof String);//False 21 System.out.println("================================"); 22 Person person = new Student(); 23 System.out.println(person instanceof Student);//true 24 System.out.println(person instanceof Person);//true 25 System.out.println(person instanceof Object);//true 26 System.out.println(person instanceof Teacher);//False 27 //System.out.println(person instanceof String);//编译报错 28 System.out.println("================================"); 29 Student student = new Student(); 30 System.out.println(student instanceof Student);//true 31 System.out.println(student instanceof Person);//true 32 System.out.println(student instanceof Object);//true 33 //System.out.println(student instanceof Teacher);//编译报错 34 //System.out.println(student instanceof String);//编译报错 35 36 } 37 }
1 package com.oop; 2 3 import com.oop.demo07.Person; 4 import com.oop.demo07.Student; 5 6 public class Application { 7 8 public static void main(String[] args) { 9 //类型之间的转换:基本类型转换 父 子 10 11 //高 低 12 Person obj = new Student(); 13 14 //student将这个对象转换为Student类型,我们就可以使用Student类型的方法了! 15 //Student student = (Student) obj; 16 //student.go(); 17 ((Student) obj).go(); 18 19 20 //子类转换成父类会丢失一些独有的方法! 21 Student student = new Student(); 22 student.go(); 23 Person person = student; 24 25 } 26 }
标签:import 小结 转换 main wrap === code 向下转型 是什么
原文地址:https://www.cnblogs.com/duanfu/p/12222595.html