多态 :父类对象引用子类实例(具有继承关系,实现关系)
引用数据类型的强转
1,关系,继承关系,实现关系
2,看图
任何时候需要使用父类对象的地方,都可以传一个子类实例
Person p=new Person ();
Student s=new Student();
method(s);
Person p1=new Student();
//方法:调用向左看,执行向右看
/*p1.eat();
//先强转,
((Student) p1).study();
s.study();
//Dome s2=(Dome) p1;//ClassCastException报错
Person p2=(Person) s;
p2.eat();
Demo1 s1=(Demo1) s;*/
}
public static void method(Person x){
//p1.eat();
/*instanceof 判断某个对象是否是某个类型,结果是布尔类型boolean
* 类型不能随便写,需要满足在继承关系链上,规则同强转
* 线上返回true,线下返回false
* */
System.out.println(x instanceof Dome);
if (x instanceof Student) {
((Student) x).study();
}else if (x instanceof Demo1) {
System.out.println("好好工作");
}
}
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200520163423925.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L20wXzQ3NjMxMjI2,size_16,color_FFFFFF,t_70#pic_center)
多态
最新推荐文章于 2023-06-28 19:31:28 发布