Java记录 -15- 面向对象之多态续

来源:互联网 发布:电信的客户端软件 编辑:程序博客网 时间:2024/06/05 00:51

Java 面向对象之多态续

  1. 多态:父类型的引用可以指向子类型的对象。

  2. 晚绑定是执行运行的时候确定类型,而不是编译的时候就进行确定。

  3. Parent p = new Child(); 当使用多态方式调用方法时,首先检查父类中是否有该方法如sing(),如果没有则编译错误,如果有则再去调用子类的该方法如sing()。

  4. 一共有两种类型的强制类型转换:

    1).向上类型转换(upcast):比如说将Cat类型转换为Animal类型,即将子类型转换为父类型。对于向上类型转换,不需要显式指定。

    2).向下类型转换(downcast):比如将Animal类型转换为Cat类型。即将父类型转换为子类型。对于向下转换,必须显式指定(必须要使用强制类型转换)。

  5. 多态经典使用:

      public class Car{

          public void run(){}

      }

      public class BMW extends Car{

          public void run(){}

      }

      public class VW extends Car{

          public void run(){}

      }

     public class TestCar{

        public static void main(String[] args){

            TestCar tc = new TestCar();           

            Car bmw = new BMW

            tc.test(bmw);

            Car vw = new VW();

            tc.test(vw);

         }

         public void test(Car car){

            car.run();

        }

     }

    test()方法接收一个Car父类参数,并调用其方法。但实际使用时,传递的是子类的对象,会对应调用子类的方法。这样所以子类都可以使用该方法。