多态性
来源:互联网 发布:玄幻网络四大名著 编辑:程序博客网 时间:2024/05/09 17:44
-----------siwuxie095
多态性的体现:
(1)方法的重载与重写
(2)对象的多态性
对象的多态性:
(1)向上转型:程序会自动完成
(2)向下转型:强制类型转换
代码:
package com.siwuxie095.pol;
class A{
publicvoid tell1() {
System.out.println("A---tell1()");
}
publicvoid tell2() {
System.out.println("A---tell2()");
}
}
class Bextends A{
//复写方法或重写方法
publicvoid tell1() {
System.out.println("B---tell1()");
}
publicvoid tell3() {
System.out.println("B---tell3()");
}
}
public class PolDemo01 {
public staticvoid main(String[] args) {
//向上转型
B b=new B();
A a=b;//或合成一步 A a=new B();
//因为tell1()是被重写的,所以调用时调用的是重写后的方法
a.tell1();
a.tell2();
System.out.println();
//向下转型
A ax=new B();//向下转型一定要先发生向上转型
B bx=(B)ax;
bx.tell1();
bx.tell2();
bx.tell3();
}
}
运行一览:
如果在向下转型时不先发生向上转型,即A ax=new A();,就会发生
类型转换异常(ClassCastException),即 这两个类之间没有明确的
指向关系
多态性的应用:
代码:
package com.siwuxie095.pol;
//父类 T
class T{
publicvoid tell1() {
System.out.println("W---tell1()");
}
}
//子类 X
class Xextends T{
publicvoid tell2() {
System.out.println("X---tell2()");
}
}
//子类 Y
class Yextends T{
publicvoid tell3() {
System.out.println("Y---tell3()");
}
}
//子类 Z
class Zextends T{
publicvoid tell4() {
System.out.println("Z---tell4()");
}
}
public class PolDemo02 {
public staticvoid main(String[] args) {
//子类执行父类方法
say(new X());//传递匿名对象进去
say(new Y());
say(new Z());
}
public staticvoid say(T t) {
t.tell1();
}
}
运行一览:
【made by siwuxie095】
- 多态性
- 多态性
- 多态性!
- 多态性
- 多态性
- 多态性
- 多态性
- 多态性
- 多态性
- 多态性
- 多态性
- 多态性
- 多态性
- 多态性
- 多态性
- 多态性
- 多态性
- 多态性
- 士兵杀敌----树状数组的应用
- JavaScript基本语法(二)
- springMVC--spring3.X注解(1)
- Tomcat 8.0 在 Windows 上的部署
- leetcode
- 多态性
- C#委托实现C++ Dll中的回调函数
- match_Parent、fill_parent和wrap_Parent区别
- leetcode
- HDU 5093 Battle ships (最大匹配)
- leetcode
- linux基础unit2
- 3.18日的总结
- lightoj 1341