Java类的初始化与垃圾清理

本文详细介绍了Java中成员变量的初始化过程,包括默认初始化、显式初始化及构造器初始化等。此外,还探讨了静态成员的初始化顺序及其执行流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Member initialization

Inside class(类), primitives(原始类型) are given default values if you don’t specify values, If you haven’t given “i” an initial value and you try to use it anyway, you’ll get a runtime error called an exception.

void f() {  
    // Error -- the local variable i may not initialized   
    int i;     
    i++;  

    int [] a, b;
    // that's right, array 'a' has been initialized
    a = new int[5];
    // wrong, since 'b' is an array
    b = 2; 
    // right, its result is default 0
    System.out.print(a[0]);
} 
class Data {     
    int i = 999; 
    // Defaults to zero    
    long l;
} 
Array initialization
int a1[];  
int[] a1;   // is the same as this! 
int a[] = new int[2];
System.out.println(a[0]);// the result is 0
Constructor initialization

Order of initialization – Order that variables/objects are defined in class.
Let’s see.

1、

class Counter {   
    int i;   
    // i will first be initialized to 0, then to 7  
    Counter() 
    {   
        i = 7; 
    }
}

2、

class Card {   
    // Before constructor 1
    Tag t1 = new Tag(1); 
    // Then constructor 4   
    Card() {     
        // Indicate we're in the constructor:     
        System.out.println("Card()");  
        // Reinitialize t3   
        t3 = new Tag(33);    
    }   
    // Before constructor 2
    Tag t2 = new Tag(2); 
    // At last, method   
    void f() {      
        System.out.println("f()");   
    }
    // Before constructor 3
    Tag t3 = new Tag(3); 
} 
order of the execution:
1   Tag(1) 
2   Tag(2) 
3   Tag(3) 
4   Card() 
5   Tag(33) 
6   f()
Process of creating an object – class Dog

1、The first time an object of type Dog is created, or the first time a static method or static field of class Dog is accessed.
2、As Dog.class is loaded, all of its static initializers are run.
3、The construction process for a Dog object first allocates enough storage for a Dog object on the heap.
4、This storage is wiped to zero, automatically setting all the primitives in that Dog object to their default values.
5、Any initializations that occur at the point of field definition are executed.
6、Constructors are executed.

Explicit static initialization
class Cup {   
    Cup(int marker) {     
        System.out.println("Cup(" + marker + ")");   
    }   
    void f(int marker) {     
        System.out.println("f(" + marker + ")");   
    } 
} 
class Cups {   
    static Cup c1;   
    static Cup c2;   
    static {     
        c1 = new Cup(1);     
        c2 = new Cup(2);   
    }   
    Cups() {     
        System.out.println("Cups()");   
    } 
} 
public class ExplicitStatic {   
    public static void main(String[] args) {     
        System.out.println("Inside main()");     
        Cups.c1.f(99);     
    }  
    //* 
    //static Cups x = new Cups();    
    //static Cups y = new Cups();  
}
The order of execution:
1   Inside 
2   main() 
3   Cup(1) 
4   Cup(2) 
5   f(99) 
The order of execution after canceling the comment at *
1   Cup(1)
2   Cup(2)
3   Cups()
4   Cups()
5   Inside main()
6   f(99)
Order of constructor calls
  1. The base-class constructor is called. This step is repeated recursively such that the very root of the hierarchy is constructed first, followed by the next-derived class, etc., until the most-derived class is reached. (追溯到基类先构造,然后一层一层向下构造子类)
  2. Member initializers are called in the order of declaration. (成员的初始化按声明顺序从上到下)
  3. The body of the derived-class constructor is called. (最后是构造器)
Conclusions:

Java allows you to group other static initializations inside a special “static clause” (sometimes called a static block) in a class. like other static initializations, is executed only once.

Cleanup

Cleanup: Finalization and Garbage Collection

Important facts about garbage collection

1、Garbage collection is not destruction
2、Your objects may not get garbage collected
3、Garbage collection is only about memory

What is finalize() for?

1、In theory: releasing memory that the GC wouldn’t
2、It’s never been reliable: promises to be called on system exit; (causes bug in Java file closing)
3、Using finalize() to detect an object that hasn’t been properly cleaned up
4、finalize() is only useful for obscure memory cleanup that most programmers will never use

You must perform cleanup

1、Must write specific cleanup method

ps:

Java GC releases memory only: any other cleanup must be done explicitly!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Antrn

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值