方法是动态绑定的,属性是静态绑定的

来源:互联网 发布:js脚本注入网页 编辑:程序博客网 时间:2024/05/05 05:11


package com.test;
/**
 * @FileName    : B.java
 * @Description : 复习下:帮助你理解方法是动态绑定,属性是静态绑定的
 * @Copyright   : PowerData Software Co.,Ltd.Rights Reserved
 * @Company     : XXXXX
 * @author      : 星辰
 * @version     : 1.0
 * Create Date  : 2014-9-5 下午04:57:24
 *
 */
class AA {
 protected int a = 2;
 protected static int b = 2;
 static void method1() {
  System.out.println("A.method1()");
 }

 void method2() {
  System.out.println("A.method2()");
 }
}

public class B extends AA {
 protected int a = 3;
 protected static int b = 3;
 // will not override A.method1()
 static void method1() {
  System.out.println("B.method1()");
 }

 // will override the A. method2()
 void method2() {
  System.out.println("B.method2()");
 }

 public static void main(String[] args) {
  AA a = new B();
  System.out.println("b:" + a.b);//2
  System.out.println("a:" + a.a);//2
  a.method1();//
  a.method2();
 }
 // //因为A里面的method1是static,编译时就静态绑定了,所以输出 A.method1搜索() a.method2();
 // //而method2()不是static方法,a是由B
 // new出来的,执行的时候会执行new它的那个类的method2()方法,所以输出B.method2(),这是java的多态性 }}
}



================结果:

b:2
a:2
A.method1()
B.method2()

0 0