zoukankan      html  css  js  c++  java
  • Java核心技术(初阶)知识点复习——[5]转型、多态、契约设计

    1.类转型

      基本类型的相互转型;

      对象类型的相互转型只限制于有继承关系的类,且仅限于向上转型(由子类变成父类);

      父类转为子类只有一种情况例外,即父类本身就是子类转化过来的(见下面的代码);

    1 Human obj1 = new Man();//可以,因为man继承于Human
    2 Man obj2 = (Man) obj1;//可以,因为obj1本身起源就是来自Man

       注:至于这种向下转型在什么情况下使用,有什么意义等碰到了我再回来补充⑧!

         (目前推断是为了【实现接口方法的多态性】:定义接口类数组时向上转型,调用某一实例的方法时向下转型,以便使用有方法体的方法)

    2.多态

      类转型带来的作用就是多态;

      作用为:1)可以以统一的接口来操纵某一类中不同的对象的动态行为;

          2)可以实现对象间的解耦;

      子类方法的方法名、形参和父类一样,但子类方法的优先级高于父类;

    1 public class Human{
    2     public void eat(){
    3         system.out.println("I can eat");
    4     }
    5 }
     1 public class Man extends Human{
     2     public void eat(){
     3         System.out.println("I can eat more");
     4     }
     5     public void plough(){
     6         Sysytem.out.println("I can also plough")
     7     }
     8 
     9     public static void main(String[] args){
    10         Man obj1 = new Man();
    11         obj1.eat(); //call Man.eat();
    12         Human obj2 = (Human) obj1;
    13         obj2.eat(); //call Man.eat();!!!从内存上来理解!!!向上转型只是把原来内存空间的一部分数据遮盖住
    14         Man obj3 = (Man) obj2;
    15         obj3.eat(); //call Man.eat();
    16 17 }

      如果这时候来测试一下,会发现这三者实际上只想的是同一块内存,所以只是临时把一部分数据遮盖住了;

    1 public static void main(String[] args){
    2      System.out.println(obj1 = obj2); //true
    3      System.out.println(obj1 = obj3); //true
    4      System.out.println(obj3 = obj2); //true
    5 }

     

    3.契约设计——基于多态性的设计思想

      [1]接口规定规范了对象应该包含的行为和方法,即接口定义了方法的名称、参数、返回值;规范了派生类的行为;

      [2]基于接口,利用转型和多态,不影响真正方法的调用,成功将调用类和被调用类解耦(decoupling);

    1 public interface Animal{
    2     public eat();
    3 }
    public class AnimalTest{
        public static void haveLunch(Animal a){
            a.eat();
        }
        havelunch(new Cat());//隐含一个向上转型:Animal a = new Cat();
    }

      [3]综上,基于契约设计,类不会直接使用另外一个类,而是采用接口形式,外部可以“空投”这个接口下的任意子类对象(此时默认实现了一个向上转型过程)

  • 相关阅读:
    分享5个viewport相关的jQuery插件
    超棒的响应式jQuery网格布局插件 grida licious
    6款不容错过的超棒倒计时jQuery插件
    分享45套2011年和2012年的高质量免费网站模板
    分享11个使用方便的免费智能手机UI套件
    推荐30款超精致的体育类型的网站设计
    HDOJ1001
    HDOJ1003
    HDOJ1000
    HDOJ1002
  • 原文地址:https://www.cnblogs.com/li7anStrugglePath/p/12731592.html
Copyright © 2011-2022 走看看