java 动态绑定 多态
2024-08-31 01:02:53
继承链中对象方法的调用规则:当前类-->父类-->爷类-->..-->祖先类(只能向上找,不能向下找)
优先级:this.method(Obj) > super.method(Obj) > this.method((super)Obj) > super.method((super)Obj)
demo代码:
public class Polymorphic { public static void main(String[] args) {
Son son=new Son();
Grandson grandson=new Grandson();
Grandson2 grandson2=new Grandson2(); son.method(); //this.method() 当前类Son有method(),就不在使用Father的method()了
grandson.method(); //super.method() 当前类Grandson没有method(),调用的是父类Son的method()
grandson.methods(); //Grandson和Son都没有methods(),向上找到Father的methods()
grandson.method(grandson); //this.method((super)Obj) 当前类以及父类中没有method(Grandson g),则找method(Son s)
grandson2.method(son); //super.method((super)Obj) Grandson2和Son都没有method(Son s),向上找到Father的method(Father f)
/* 结果:
* Son method()
Son method()
Father methods()
G S
F S
*/
Father father_son = new Son(); //声明了一个Father对象,但创建了一个Son对象,father_son是对象的引用,指向创建的Son对象
grandson.method(father_son); //结果:F F 因为参数代表的是声明的对象,并非创建的对象
} }
class Father {
public void method(){
System.out.println("Father method()");
}
public void methods(){
System.out.println("Father methods()");
}
public void method(Father f){
System.out.println("F F");
}
public void method(Son s){
System.out.println("F S");
}
}
class Son extends Father{
public void method(){
System.out.println("Son method()");
}
}
class Grandson extends Son{
public void method(Son s){
System.out.println("G S");
}
}
class Grandson2 extends Son{
}
最新文章
- Django发送邮件
- (原创)古典主义——平凡之美 佳作欣赏(摄影,欣赏)
- Tips6:用[HideInInspector]在Inspector中隐藏变量
- 【反射】——Autofac 类型注册
- ThinkPHP3.2 分页实现
- 使用WinINet和WinHTTP实现Http訪问
- MVC ViewData和ViewBag
- JSP 表单request内容
- BZOJ 2527 Meteors
- bootbox的使用
- GIT入门笔记(20)- 使用eclipse 基于 git 开发过程梳理
- vim编辑器常见命令归纳大全
- 驰骋工作流引擎-流程数据md5加密
- 初识服务器和Linux
- UDP套接字编程 返回系统时间
- executequery要求已打开且可用的connection,连接的当前状态为已关闭
- Django 调用报错 "; ImportError: Couldn't import Django. ";
- python - 练习统计随机字母数据
- 【vue】遇到的问题
- Qt布局管理: 停靠窗口QDockWidget类(纯代码实现)
热门文章
- 邮件服务器安装--Postfix + Dovecot + Squirrelmail--CentOS 6.4
- JAR包结构,META-INF/MANIFEST.MF文件详细说明[全部属性][打包][JDK]
- 【Python基础】lpthw - Exercise 44 继承与组合
- Java如何获取JSON数据中的值
- war 包tomcat部署和maven的tomcat插件部署的不同
- macOS 版微信小助手,支持微信多开、防撤回、远程控制mac、自动回复等等
- httpappplication 和 httpmodule 的理解(转载,写的很好)
- 原生js获取 一个dom元素距离页面可视区域的位置值 -- getBoundingClientRect
- validationEngine 使用
- OpenStack-Neutron-Fwaas-代码【二】