instanceof (类型转换) ~ 引用类型,判断一个对象是什么类型~
package com.baidu.oop; import com.baidu.oop.demo06.Person; import com.baidu.oop.demo06.Student; public class Application { public static void main(String[] args) { //一个对象的实际类型是确定的 //new Student(); //new Person(); //可以指向的引用类型就不确定了,父类的引用指向子类的类型 //Student能调用的方法都是自己的或者继承父类的 Student s1 = new Student(); //Person 父类型,可以指向子类,但是不能调用子类独有的方法 Person s2 = new Student();//父类的引用指向子类的类型 Object s3 = new Student(); //对象能执行那些方法,主要看对象左边的类型,和右边关系不大 ((Student)s2).eat();//子类重写了父类的方法,执行了子类的方法 //s1.eat(); } } package com.baidu.oop.demo06; public class Student extends Person{ @Override public void run() { System.out.println("son"); } public void eat(){ System.out.println("eat"); } } package com.baidu.oop.demo06; public class Person { public void run() { System.out.println("run"); } } /* 多态注意事项: 1.多态是方法的多态,属性没有多态 2.父类和子类,有联系 类型转换异常! ClassCastException! 3.存在条件:继承关系,方法需要重写,父类引用指向子类对象 father f1 = new Son(); 1.static方法,属于类他不属于实例 2.final常量 3.privat方法 */ //instanceof和类型转换 package com.baidu.oop; import com.baidu.oop.demo06.Person; import com.baidu.oop.demo06.Student; import com.baidu.oop.demo06.Teacher; public class Application { public static void main(String[] args) { //Object > String //Object > Person > Teacher //Object > Person > Student Object object = new Student(); //System.out.println(X instanceof Y);//能不能编译通过 System.out.println(object instanceof Student);//True System.out.println(object instanceof Person);//T System.out.println(object instanceof Object);//T System.out.println(object instanceof Teacher);//False System.out.println(object instanceof String);//F System.out.println("--------------------------------------------"); Person person = new Student(); System.out.println(person instanceof Student);//True System.out.println(person instanceof Person);//T System.out.println(person instanceof Object);//T System.out.println(person instanceof Teacher);//False //System.out.println(person instanceof String);//编译报错 Student student = new Student(); System.out.println("--------------------------------------------"); System.out.println(student instanceof Student);//True System.out.println(student instanceof Person);//T System.out.println(student instanceof Object);//T //System.out.println(student instanceof Teacher);//编译出错 //System.out.println(person instanceof String);//编译报错 } } import com.baidu.oop.demo06.Person; import com.baidu.oop.demo06.Student; public class Application { public static void main(String[] args) { //类型之间的转化:父 子 //高 低 Person obj = new Student(); //Student将这个对象转换为Student类型,我们就可以使用Student类型的方法了 Student student = (Student)obj; student.go(); //((Student) obj).go(); }java封装继承以及多态(含代码) (2)
内容版权声明:除非注明,否则皆为本站原创文章。