http://www.51testing.com/?uid-283585-action-viewspace-itemid-235141
一:c#初始化顺序
1。类成员变量初始化先于类的构造函数
2。静态成员变量先于实例变量
3。子类成员变量先于父类成员变量 java相反
4。父类构造函数先于子类构造函数
参考示例:
using System;
//using System.Collections.Generic;
//using System.Linq;
//using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
// DriveB d = new DriveB();
DriveC f = new DriveC();
}
}
class BaseA
{
static DisplayClass a = new DisplayClass("基类静态成员初始化");
DisplayClass BaseA_c = new DisplayClass("基类实例变量BaseA_c初始化");
public BaseA()
{
Console.WriteLine("基类构造方法被调用A");
}
}
class DriveB : BaseA
{
static DisplayClass DriveB_b = new DisplayClass("继承类静态成员DriveB_b初始化");
//static BaseA DriveB_a = new BaseA();
DisplayClass DriveB_c = new DisplayClass("继承类实例变量DriveB_c初始化");
public DriveB()
{
Console.WriteLine("继承类构造方法被调用B");
}
}
class DriveC : DriveB
{
static DisplayClass DriveC_d = new DisplayClass("继承类静态成员DriveC_d初始化");
DisplayClass DriveC_e = new DisplayClass("继承类静态成员DriveC_e初始化");
public DriveC()
{
Console.WriteLine("继承类构造方法被调用C");
}
}
class DisplayClass
{
public DisplayClass(string diplayString)
{
Console.WriteLine(diplayString);
Console.WriteLine();
}
}
}
输出结果为:
继承类静态成员DriveC_d初始化
继承类静态成员DriveC_e初始化
继承类静态成员DriveB_b初始化
继承类实例变量DriveB_c初始化
基类静态成员初始化
基类实例变量BaseA_c初始化
基类构造方法被调用A
继承类构造方法被调用B
继承类构造方法被调用C
摘抄自:http://social.microsoft.com/Forums/zh-CN/visualcshartzhchs/thread/6854c902-9396-4e79-a398-3346f51512f1
二:java 初始化顺序
先父类静态成员初始化,后子类静态成员初始化
然后是父类成员,父类构造函数,最后是子类成员,子类构造函数
参考示例:
class Parent {
private static int s = getS("父类静态成员");
private int num = getNum();
public Parent() {
System.out.println("父类构造函数");
}
private static int getS(String string) {
System.out.println(string);
return 47;
}
public int getNum() {
System.out.println("父类私有成员");
return num;
}
public static void setS(int s) {
Parent.s = s;
}
}
class Child extends Parent {
private int num = prt("子类私有成员");
private static int s = getS("子类静态成员");
public static void setS(int s) {
Child.s = s;
}
public Child() {
System.out.println("子类构造函数");
}
public void setNum(int num) {
this.num = num;
}
private int prt(String string) {
System.out.println(string);
return 5;
}
public static int getS(String string) {
System.out.println(string);
return s;
}
}
public class Tee {
/**
* @param args
*/
public static void main(String[] args) {
Child c = new Child();
c.setNum(100);
// 为什么输出的是0
System.out.print(c.getNum());
// Child cStatic = new Child();
// cStatic.setS(100);
// System.out.println(cStatic.getS("s"));
}
}
最后输出结果:
父类静态成员
子类静态成员
父类私有成员
父类构造函数
子类私有成员
子类构造函数
父类私有成员
0
摘抄自:http://www.blogjava.net/aqiangjx/archive/2008/03/12/185705.html