Instanceof:
判断一个对象是什么类型的~,可以判断两个类之间是否存在父子关系
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 }
多态小结:
1、前提:父类引用指向子类对象
2、把子类转换为父类,向上转型:会丢失一些独有的方法
3、把父类转换为子类,向下转型:强制转换
好处:
方便方法的调用,减少重复的代码,可以有效的提升利用率!是代码变的简洁
抽象:编程思想:三大特性,封装、继承、多态! 后面有抽象类!接口!