zoukankan      html  css  js  c++  java
  • 面向对象——多态(资源来自网络 版权非本人)

     1 package com.hzxx.demo;
     2 
     3 public class Polymorphism {
     4 
     5     public static void main(String[] args) {
     6         Person person = new Student();
     7         /*
     8          * 父类引用只能调用父类中存在的方法和属性,
     9          * 不能调用子类的扩展部分,
    10          * 因为父类引用指向的是堆中子类对象继承的父类
    11          * 这里父类person只有一个eat方法
    12          */
    13         person.eat();// 只能调用子类已经重写的父类Person的eat()方法
    14        /*
    15         * instanceof
    16         * 这个对象是否是这个特定类或者是它的子类的一个实例
    17         */
    18         if (person instanceof Student) {
    19             Student stu1 = (Student) person;//把超类转换成子类    
    20             /*
    21              * 调用子类才有的方法
    22              * 但是如果强制把超类转换成子类的话,
    23              * 就可以调用子类中新添加而超类没有的方法了
    24              */
    25             stu1.study();
    26             stu1.walk();
    27         }
    28 
    29         
    30         Behavior behavior = new Student();
    31         behavior.walk();// 只能调用子类已经重写的接口Behavior的walk()方法
    32         if (behavior instanceof Student) {
    33             Student stu2 = (Student) behavior;
    34             /*
    35              * 调用子类才有的方法
    36              */
    37             stu2.study();
    38             stu2.eat();
    39         }
    40     }
    41 }
    42 
    43 class Student extends Person implements Behavior {
    44 
    45     @Override
    46     public void eat() {
    47         super.eat();
    48     }
    49 
    50     @Override
    51     public void walk() {
    52         System.out.println("..人都要走路");
    53     }
    54 
    55     public void study() {
    56         System.out.println("..学生要学习");
    57     }
    58 
    59 }
    60 
    61 class Person {
    62     public void eat() {
    63         System.out.println("父类===人都要吃饭");
    64     }
    65 }
    66 
    67 interface Behavior {
    68     void walk();
    69 }

    大概就是说:超类只能调用超类的方法 不能调用子类的扩展(重写 或者 重载)方法  如果想调用 就要强制转换成子类 

    同样接口也是一样  想要调用扩展的方法要强制转换 (不知道是不是必须要强制换换才能调用 可能还有别的方法 )

  • 相关阅读:
    Win10 VS2013 PCL1.8.1和依赖项VTK8.0.1, QHuall(2.15.2), FLANN1.9.1,Boost1.59.0,Zbil1.2.11和libPNG1.6.34编译安装
    Boost log中的几个问题
    Linux 使用静态库注意事项
    Windows中lib和DLL区别和使用
    CMake: ELF文件加载动态库的位置
    CMake 默认编译、链接选项
    ld 链接选项-L,-rpath-link,-rpath
    动态库的链接和链接选项-L,-rpath-link,-rpath
    Linux共享对象之编译参数 -fPIC
    ny509 因子和阶乘
  • 原文地址:https://www.cnblogs.com/zhbx/p/8615764.html
Copyright © 2011-2022 走看看