java-多态

package com.flowe.oop.demo04;

public class Person {
    public  void run(){
        System.out.println("run");
    }
}

/*
多态注意事项:
1.多态是方法的多态,属性没有多态
2.父类和子类,有联系,类型转换异常 ClassCastException!
3.存在条件:继承关系,方法需要重写,父类引用指向子类对象
 */
package com.flowe.oop.demo04;

public class Student extends Person{

    @Override
    public void run() {
        System.out.println("son");
    }
    public void eat(){
        System.out.println("ear");
    }
}
package com.flowe.oop;

import com.flowe.oop.demo04.Person;
import com.flowe.oop.demo04.Student;

public class Application {

    public static void main(String[] args) {

        Student s1 = new Student();
        Person s2 = new Student();
        Object s3 = new Student();


        ((Student) s2).eat();
        s1.eat();
    }
}


多态:统一方法可以根据发送对象的不同而采取多种不同的行为方式
一个对象的实际类型是确定的,但可以指向对象的引用的类型很多
多态存在的条件:
有继承关系
子类重写父类方法
父类引用指向子类对象
多态是方法的多态 属性没有多态性
instanceof

package com.flowe.oop.demo04;

public class Person {
    public  void run(){
        System.out.println("run");
    }
}
package com.flowe.oop.demo04;

public class Teacher extends Person{
}
package com.flowe.oop.demo04;

public class Student extends Person{


}
package com.flowe.oop;

import com.flowe.oop.demo04.Person;
import com.flowe.oop.demo04.Student;
import com.flowe.oop.demo04.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(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

    }
}
package com.flowe.oop.demo04;

public class Person {
    public  void run(){
        System.out.println("run");
    }
}
package com.flowe.oop.demo04;

public class Student extends Person{
    public void go(){
        System.out.println("go");
    }


}
package com.flowe.oop;

import com.flowe.oop.demo04.Person;
import com.flowe.oop.demo04.Student;
public class Application {

    public static void main(String[] args) {
        //类型之间的转换 高转低需强转 低转高不需要

        Person obj = new Student();

        //student对象转换成Student,我们就可以使用Student类型的方法了
        Student student = (Student) obj;
        student.go();

    }
}
/*
1.父类引用指向子类的对象
2.把子类转换为父类,向上转型
3.把父类转换为子类,向下转型 需要强制转换
4.方便方法的调用,减少重复的代码;简洁
 */

posted on 2022-05-12 10:39  言语说  阅读(26)  评论(0)    收藏  举报

导航