多态和instanceof

发布时间 2023-03-26 14:21:48作者: 离001

多态

动态编译:类型:可扩展性

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

一个对象的实际类型是确定的,但可以指向对象的引用类型有很多

 

多态存在的条件

  1. 有继承关系

  2. 子类重写父类方法

  3. 父类引用指向子类

 

注意

多态是方法的多态,属性没有多态性

 

 

异常

类型转换异常:ClassCastException

 

不能重写的

 

  1. static方法,属于类,不属于实例

  2. final 常量

  3. private方法

 

 

主方法

public class example {
   public static void main(String[] args){

       //一个对象的实际类型是确定的的
       //可以指向的引用类型就不确定了
       //父类的引用指向子类

       //Student能调用的方法都是自己的或者继承父类的
       Student s1 = new Student();
       //父类可以指向紫烈,但是不能调用子类独有的方法
       Person s2 = new Student();
       Object  s3 = new Student();


       s2.run();
       s1.run();

       s1.eat();
      ((Student)s2).eat();//强转!!!



  }
}

 

父类

public class Person {

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

  }

}

子类

public class Student extends Person{
   @Override
   public void run() {
       System.out.println("son");
  }
   public void eat(){
       System.out.println("eat");
  }
}

 

 

关键字

instanceof

要求对象的两个类要有包含关系,才不报错。

public class example {
   public static void main(String[] args) {

       //Object > String
       //Object > Person > Teacher
       //Object > Person > Student

       //System.out.println(X instanceof Y);//能不能编译通过
       //有父子关系则通过


       Object object = new Student();
       System.out.println(object instanceof Student);//ture
       System.out.println(object instanceof Person);//ture
       System.out.println(object instanceof Object);//ture
       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 Person);//ture
       System.out.println(person instanceof Object);//ture
       System.out.println(person instanceof Teacher);//false
       //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);//ture
       System.out.println(student instanceof Object);//ture
       //System.out.println(student instanceof Teacher);//编译报错
       //System.out.println(student instanceof String);//编译报错

  }
}

子类转换为父类,可能丢失自己本来的一些方法