多态

同一方法可以根据发送对象的不同而采用多种不同的行为方式。

多态存在的条件

  • 有继承关系
  • 子类重写父类的方法
  • 父类引用指向子类对象

多态的注意事项

  1. 多态是方法的多态,属性没有多态
  2. 父类和子类,有联系(如狗转换成猫就会出现类型转换异常ClassCastException!
  3. 部分方法不能重写:1.static 2.final 3.private

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

}
public class Student extends Person{
    @Override
    public void run() {
        System.out.println("son");
    }
}
public class Application {
    public static void main(String[] args) {

        Student s1 = new Student();//能调用自己的或继承父类的方法

        Person s2 = new Student();//父类的引用指向子类,不能调用子类独有的方法
        //对象能执行哪些方法,主要看对象左边的类型,和右边关系不大
        s1.run();
        s2.run();//子类重写了父类的方法,执行子类的方法
    }
}

instanceof

判断是否具有父子关系

  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
        System.out.println("============================");
        Person person = new Student();
        System.out.println(person instanceof Student);//ture
        System.out.println(person instanceof Teacher);//false
        System.out.println(person instanceof Person);//true
        System.out.println(person instanceof Object);//true
        //System.out.println(person instanceof String);编译报错
        System.out.println("==============================");
        Student student = new Student();
        System.out.println(student instanceof Student);//ture
        System.out.println(student instanceof Person);//true
        System.out.println(student instanceof Object);//true
        //System.out.println(student instanceof Teacher);编译报错
        //System.out.println(student instanceof String);编译报错
posted @ 2021-05-28 18:02  Theshy-Riven  阅读(39)  评论(0)    收藏  举报