---
title: "java解惑–学习总结二"
author: "pclfs1983"
date: "2009-08-12T13:23:27Z"
tags: []
slug: "java"
draft: false
lastmod: "2009-08-12T13:23:27Z"
id: 445455
url: "https://pclfs1983.iteye.com/blog/445455"
---

1.静态方法

public class Test {

   public static void main(String args) {  

            Super woofer=new Super();

            Super nipper=new Sub();

            Sub c = new Sub();

            woofer.bark();

            nipper.bark();

            c.bark();

    }

}

class Super {  

    public static void bark(){

       System.out.println(”bark”);

    } 

}

class Sub extends Super {  

   public static void bark(){

            System.out.println(”cc”);

    }  

}

结果是：bark  bark  cc

原因是：对静态方法的调用不存在任何动态的分派机制。当一个程序调用了一个静态方法时，要被调用的方法都是在编译时刻被选定的，而这种选定是基于修饰符的编译期类型而做出的，修饰符的编译期类型就是我们给出的方法调用表达式中等号左边部分的名称。

2.类初始化顺序

public class Test1 {

    public static int k=0;

    public static Test1 t1=new Test1(”t1″);

    public static Test1 t2=new Test1(”t2″);

    public static int i=print(”i”);

    public static int n=99;

    public int j=print(”j”);

    {

        print(”构造块”);

    }

   

    static{

        print(”静态块”);

    }

 

    public Test1(String str){

  System.out.println((++k)+”:”+str+”    i=”+i+”    n=”+n);

        ++i;++n;

    }

   

    public static int print(String str){

        System.out.println((++k)+”:”+str+”    i=”+i+”    n=”+n);

        ++n;

        return ++i;

    }

    public static void main(String…strings ){

        Test1 t=new Test1(“init”);

    }

}

输出结果：

1:j    i=0    n=0

2:构造块    i=1    n=1

3:t1    i=2    n=2

4:j    i=3    n=3

5:构造块    i=4    n=4

6:t2    i=5    n=5

7:i    i=6    n=6

8:静态块    i=7    n=99

9:j    i=8    n=100

10:构造块    i=9    n=101

11:init    i=10    n=102

注：类的初始化顺序是（静态变量、静态初始化块）>（变量、初始化块）>构造器。但是当这个类中存在这个类的静态类实例对象的时候(比如: static Test1 t1=new Test1(”t1″))，则这个对象初始化时会先初始化非静态的成员，然后调用构造函数。一个实例对象初始化一次成员变量，而类变量只初始化一次。如果是父子都存在静态变量和变量,则初始化的顺序是: 子类的静态变量和静态初始化块的初始化是在父类的变量、初始化块和构造器初始化之前就完成.