---
title: "Java初始化顺序"
author: "Vikings825"
date: "2011-03-20T21:05:00Z"
tags: []
categories: ["编程语言"]
slug: "java"
draft: false
lastmod: "2011-03-20T21:05:00Z"
id: 968711
url: "https://vikings825.iteye.com/blog/968711"
---

当一个对象被创建时，初始化是按照一下顺序完成的：

设置成员的值为默认的初始化值（0,false,null）。
调用对象的构造方法（但是还没有执行构造方法体）。
调用父类的构造方法。
使用初始化程序和初始块初始化成员。
执行构造方法体。


贴两段代码，如果这两段代码想通了，对象初始化就没有问题了。

```java
class A{
  int a = f();
  int f(){
    return 1;
  }
}

class B extends A{
  int b = a;
  int f(){
    return 2;
  }
}

public class Demo1{
  public static void main(String []args){
    B bodj = new B();
    System.out.println(bodj.b);
  }
}
```



```java
class A{
  int a = f();
  int f(){
    return 1;
  }
}

class B extends A{
 int b = 37;
 int f(){
   return b;
 }
}

public class Demo2{
  public static void main(String []args){
    B bodj = new B();
　　System.out.println(bodj.a);
    System.out.println(bodj.f());
  }
}
```


慢慢想吧！运行出的结果和你想的一样，那恭喜你了

这还没有完，这个只是默认的情况，你还遇到过，
> super,this
关键字吧！
它们两兄弟又是另一码事了。
this指向本类，super指向超类，它们在构造函数中是如何使用的呢？

this用法，自己给自己贴段代码下来好理解一些，

```java
public class Demothis{
  String name;
  Demothis(String input){
    name = input;
  }
  Demothis(){
    this("Helllo Demothis");
  }
  public static void main(String []args){
    Demothis p1 = new Demothis("Hello");
    Demothis p2 = new Demothis();
  }
}
```

这样就好理解了，但是要注意的是：

> 在构造器重，如果要使用关键字this的话，那么必须放在构造器的第一行，如果不这样将会导致编译错误


super用法和this 差不多一样，就是指向父类，其余都差不多的。


> **自勉** writes:
> 
> 这些都是基础的基础，自己记录下来，自己提醒自己。