Java实例变量与类变量

Author Avatar
Sarience 5月 03, 2017
  • 在其它设备中阅读本文章

此文只是个人的查漏补缺,不会很全面地去解析,所以想要系统学习的童鞋请移步疯狂java讲义一书或其他博客吧,就酱<( ̄︶ ̄)>~

实例变量与类变量

实例变量:在类体内没有用static修饰的成员变量,又称非静态变量。
类变量:在类体内用static修饰的成员变量,又称静态变量。

  1. 实例变量初始化时机
    除了静态方法->代码块—>构造方法的顺序,对实例变量初始化还有个顺序:赋值语句保持在源代码中的顺序,如下两段代码:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    package com.douya.day9;
    /**
    * Created by douya on 17-5-3.
    */
    public class FiledInitial {
    public static class Exam {
    int count = 20;
    {
    count = 30;
    }
    public Exam() {
    System.out.println("count:" + count);
    }
    }
    public static void main(String[] args) {
    new Exam();
    }
    }

count:30

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package com.douya.day9;
/**
* Created by douya on 17-5-3.
*/
public class FiledInitial {
public static class Exam {
{
count = 30;
}
int count = 20;
public Exam() {
System.out.println("count:" + count);
}
}
public static void main(String[] args) {
new Exam();
}
}

count:20

  1. 类变量的初始化时机
    与实例变量一致,遵循源码中的顺序,但是为了更加了解static的机制,我们看看下面这段代码和执行结果:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package com.douya.day9;
/**
* Created by douya on 17-5-3.
*/
class Price {
final static Price INSTANCE = new Price(2.8);
static double initPrice = 20;
double currentPrice;
public Price(double discount) {
currentPrice = initPrice - discount;
}
}
public class StaticPrice {
public static void main(String[] args) {
System.out.println(Price.INSTANCE.currentPrice);
Price price = new Price(2.8);
System.out.println(price.currentPrice);
}
}

-2.8
17.2

这段代码,从表面上看,结果应该输出两个17.2才对,实际输出却是-2.8,17.2
让我们来分析一下 代码的执行过程:

  1. 第一次用到Price这个类时,程序对Price进行初始化,初始化分两个阶段:第一个阶段,为类变量分配内存空间;第二阶段,初始化代码顺序和为变量赋值;
  2. 这样就很好理解了,第一阶段的时候,系统为INSTANCE,initPrice两个类变量分配内存空间,此时INSTANCE,initPrice的值默认为null,0;
  3. 接着进入第二阶段,为INSTANCE,initPrice赋值,为INSTANCE赋值时,调用Price(2.8),创建Price实例,并立即为currentPrice赋值,而此时的initPrice值为0,所以计算出的currentPrice为-2,8。