Java动态绑定

1. 动态绑定

将一个方法调用同一个方法主体关联起来被称作绑定。

在运行时根据对象的类型进行绑定,叫做后期绑定或运行时绑定。Java中除了static方法和final

例如,下面定义了一个Shape类型的变量,这是个Shape引用,由于后期绑定,赋予其子类Circle的一个对象引用,最终调用的是Circle.draw()方法。

复制代码
 1 package com.khlin.binding.test;
 2 
 3 public class App {
 4     public static void main(String[] args) {
 5         Shape shape = new Circle();
 6         shape.draw();
 7     }
 8 }
 9 
10 class Shape {
11     public void draw() {
12         System.out.println("i m a shape...");
13     }
14 }
15 
16 class Circle extends Shape {
17     public void draw() {
18         System.out.println("i m a circle...");
19     }
20 }
复制代码

输出:i m a circle...

2.没有动态绑定的缺陷

任何域都将由编译器解析,因此不是多态的。

静态方法也不是多态的。

来看下面的例子:

复制代码
 1 package com.khlin.binding.test;
 2 
 3 public class App {
 4     public static void main(String[] args) {
 5         // Shape shape = new Circle();
 6         // shape.draw();
 7 
 8         Shape shape = new Triangel();
 9         /** 直接访问域,得到的是0,说明域无法动态绑定 */
10         System.out.println("shape field[degreeOfAngels]:"
11                 + shape.degreeOfAngels);
12         /** 调用方法,得到180,说明是动态绑定 */
13         System.out.println("shape [getDegreeOfAngels() method]:"
14                 + shape.getDegreeOfAngels());
15         /** 静态方法无法动态绑定 */
16         shape.print();
17         /** 静态域同样无法动态绑定 */
18         System.out.println("shape field[lines]:" + shape.lines);
19     }
20 }
21 
22 class Shape {
23     /** 内角之和 */
24     public int degreeOfAngels = 0;
25 
26     /** 共有几条边 */
27     public static final int lines = 1;
28 
29     public int getDegreeOfAngels() {
30         return degreeOfAngels;
31     }
32 
33     public void draw() {
34         System.out.println("i m a shape...");
35     }
36 
37     public static void print() {
38         System.out.println("printing shapes...");
39     }
40 }
41 
42 class Triangel extends Shape {
43     /** 内角之和 */
44     public int degreeOfAngels = 180;
45 
46     /** 共有几条边 */
47     public static final int lines = 3;
48 
49     public int getDegreeOfAngels() {
50         return degreeOfAngels;
51     }
52 
53     public void draw() {
54         System.out.println("i m a triangel...");
55     }
56 
57     public static void print() {
58         System.out.println("printing triangel...");
59     }
60 }
复制代码

输出结果是:

shape field[degreeOfAngels]:0
shape [getDegreeOfAngels() method]:180
printing shapes...
shape field[lines]:1

posted @   kingsleylam  阅读(505)  评论(0编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示