luohzzz

导航

多态

![在这里插入图片描述](https://img-blog.csdnimg.cn/img_convert/fbfb0495a422e11e3626cd05345eb653.png#pic_center)
![在这里插入图片描述](https://img-blog.csdnimg.cn/img_convert/a0c686cc9e2094fed136e2ccb2ef4e7a.png#pic_center)
~~~java
public class Application1 {
public static void main(String[] args) {

Object object = new Student();
//System.out.println(x instanceof y);//能不能通过就看是否存在父子关系!!

//object>person>student
//object>person>teacher
//object>String

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

//-----------------------------------------------------------------------------------------------------------
//一个对象的实际类型是确定的
//new Student();

//但是可以指向的引用类型就不确定:父类的引用指向子类
Student s1 = new Student();
//Student 能调用自己的方法好和extends父类的方法
Person s2 = new Student();
//Person 能调用自己的方法,但是不能调用子类的方法
Object s3 = new Student();

s1.eat();
s1.run();
s2.run();
//类型转换
((Student) s2).eat();
/*
Person a = new Student();
转换
Student student = (Student) a;
完成转换
student.go();
----------------------------------------
((Student) a).go():
*/
}
}
----------------------------------
public class Person {
public void run(){
System.out.println("run");
}
}
/*
多态注意点
1、多态是方法的多态,不是属性的多态
2、父类和子类 与联系。 类型转换异常!classcastexception!
3、存在条件:有extends关系 方法要重写 父类的引用指向子类 father f1 = new son():
*/----------------------------------------------------
public class Student extends Person{
@Override
public void run() {
System.out.println("son");//方法的重写
}
public void eat(){
System.out.println("ear");
}
}
------------------------------------------------------------
public class Teacher extends Person{
}

posted on 2021-05-01 23:16  luohzzz  阅读(28)  评论(0编辑  收藏  举报