zoukankan      html  css  js  c++  java
  • 多态产生的条件

     1
       // Son2 类
    1 package com.demo13;
    2 
    3 public class Son2 extends Father{
    4     @Override
    5     public void love() {
    6         System.out.println("Son2 love");
    7     
    8     }
    9 }
     1
      //Son2 类
    package com.demo13; 2 3 public class Son extends Father{ 4 public void say(){ 5 System.out.println("Son say..."); 6 } 7 public void love() { 8 System.out.println("Son love"); 9 } 10 }
    
    
    
    //Test 测试类
    package com.demo13; 2 3 public class Test { 4 public static void main(String[] args) { 5 //1- 子类可以自动转换成父类; 6 //父类必须在子类转换成父类的基础上,才能转换成父类 7 Father f = new Son();//正确,自动向上转换 8 Son s = (Son)f;//正确 9 10 /** 11 * 以下代码会报ClassCastException(类型转换异常) 12 */ 13 /*Father f1 = new Father(); 14 Son s1 = (Son)f1; */ 15 16 //2- 声明什么类型,就只能调用什么类型内的方法 17 Father ff = new Father();//只能调用Father中的方法 18 Son ss = new Son(); //只能调用Son中以及继承下来的方法 19 Father f3 = new Son();//只能调用father中的方法 20 Son s3 = (Son)f3;//只能调用Son中以及继承下来的方法 21 22 //3- new的什么类型,就真正运行什么类型的方法。 23 ff.love(); 24 ss.love(); 25 f3.love();//Son重写后的方法 26 s3.love(); 27 28 /** 29 * 总结:多台产生的条件 30 * 1- 继承 31 * 2- 子类重写父类方法 32 * 3- 声明父类,创建子类,并将声明的父类引用子类对象(即父类对象引用子类对象) 33 * 4- 父类调用被重写的方法 34 */ 35 //以下实现了多态 36 test(new Son()); 37 test(new Son2()); 38 39 } 40 41 private static void test(Father f) { 42 f.love(); 43 44 } 45 46 }

     1
      // Father 类
    package com.demo13; 2 3 public class Father { 4 public void show() { 5 System.out.println("Father show"); 6 7 } 8 public int add(int x,int y){ 9 return x + y; 10 } 11 public void love(){ 12 System.out.println("Father love"); 13 } 14 }


  • 相关阅读:
    WIFI:802.11无线LAN
    如何使你的PPT更高调
    windows的注册表有什么用?
    Steeltoe之Config客户端篇
    初探Spring Cloud Config
    .NET Core开发日志——ADO.NET与SQL Server
    .NET Core开发日志——Linux版本的SQL Server
    .NET Core开发日志——视图与页面
    .NET Core开发日志——Filter
    .NET Core开发日志——Model Binding
  • 原文地址:https://www.cnblogs.com/zqq3436/p/5334097.html
Copyright © 2011-2022 走看看