java - 谁能解释下为什么输出是1,0吗
PHPz
PHPz 2017-04-18 10:03:44
0
1
327
class Singleton{
    private  static Singleton instance=new Singleton();
    public static int count;
    public static int count1=0;
    private Singleton(){
        count++;
        count1++;
        
    }
    public static Singleton  getInstance(){
        return instance;
    }
    
}
public class SingleTonDemo {
    public static void main(String[] args) {
        Singleton  instance=Singleton.getInstance();
        System.out.println(instance.count); //1
        System.out.println(instance.count1);//0
    }
PHPz
PHPz

学习是最好的投资!

모든 응답(1)
Peter_Zhu

변수 초기화 순서 때문입니다.

  1. Singleton 객체를 생성합니다. 이때 countcount1은 모두 1

    입니다. 으아악
  2. 정적 초기화count1, 여기서 count10

    에 할당됩니다. 으아악
  3. 2개를 원하면 1개가 필요합니다. instance 아래에 count1 초기화를 배치하면 됩니다.

    으아악
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿