多态
来源:互联网 发布:雅诗兰黛眼霜 知乎 编辑:程序博客网 时间:2024/06/17 20:26
1、概念
(1)多态是同一个行为具有多个不同表现形式或形态的能力。
(2)三个必要条件:继承(或实现)、重写(或重载)、向上转型
(3)向上转型
Father f = new Son();//父类引用指向子类实例
(4)向下转型
Son s = (Son)new Father();//父类对象强制转换为子类对象
2、代码示例
求下面程序输出结果:
public class A { public String show(D obj) { return ("A and D"); } public String show(A obj) { return ("A and A"); } }public class B extends A{ public String show(B obj){ return ("B and B"); } public String show(A obj){ return ("B and A"); } }public class C extends B{}public class D extends B{}public class Test { public static void main(String[] args) { A a1 = new A(); A a2 = new B(); B b = new B(); C c = new C(); D d = new D(); System.out.println("1--" + a1.show(b)); System.out.println("2--" + a1.show(c)); System.out.println("3--" + a1.show(d)); System.out.println("4--" + a2.show(b)); System.out.println("5--" + a2.show(c)); System.out.println("6--" + a2.show(d)); System.out.println("7--" + b.show(b)); System.out.println("8--" + b.show(c)); System.out.println("9--" + b.show(d)); }}
代码输出:
1--A and A2--A and A3--A and D4--B and A5--B and A6--A and D7--B and B8--B and B9--A and D
(1)向上转型之后,父类引用只能调用父类中的成员,若父类中的成员在子类中重写,则只能调用子类的成员,“子类优先”。
(2)子类对象的引用,能调用子类中的所有成员,以及父类中的非私有成员,若重写了父类中的成员,则只能调用子类的成员,“子类优先”。
阅读全文
0 0
- 多态
- 多态
- 多态
- 多态
- 多态
- 多态
- 多态
- 多态
- 多态
- 多态
- 多态
- 多态
- 多态
- 多态
- 多态
- 多态
- 多态
- 多态
- Grunt 入门使用
- 自己进化的Unity人工智能(三)
- 关于spring boot 内嵌tomcat 在window上启动,处理请求卡死---阿里云服务器有瑕疵
- QQ列表展开收缩扩展(自定义属性,索引值练习)
- linux服务器inode节点占用过高
- 多态
- solr安装配置,两种方法
- 注释最全的Android购物车简单实现,复制可用,阅读可懂
- 排序-选择排序
- 学习激励一下自己
- 怎么用svg画一个圆圈(一)
- 前端数据的展示遇到应table展示时
- Core Animation实战二(寄宿图)
- msyql全局搜索字段所在位置