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

原文地址:https://www.cnblogs.com/kingsleylam/p/5533208.html