zoukankan      html  css  js  c++  java
  • Initializing Fields

    Common practice of initializing fields at the beginning of a class as following.

    1 public class InitializingFieldsTest {
    2   public static int age = 23;
    3   public boolean flag = false;
    4 }

    Note:  It is not necessary to declare fields at the beginning of the class definition, although this is the most common practice.

       It is only necessary that they be declared and initialized before they are used.

    Static Initializing Blocks

    1 static {
    2    // code to initialize class variables
    3 }

    Note: A class can have any number of static initialization blocks, and they can appear anywhere in the class body.

    Initializing Instance Members

      Normally, we initialize instance variables in a constructor. There are two alternatives to do this.

      Initializer blocks 

     1 public class InitializingFieldsTest {
     2   public int age;
     3   public boolean flag;
     4 
     5   // Initializer block for instance variables
     6   {
     7     age = 24;
     8     flag = true;
     9   }
    10   // can omit the constructor
    11 //  InitializingFieldsTest(){
    12 //    age = 24;
    13 //    flag = true;
    14 //  }
    15 
    16   public static void main(String[] args) {
    17     InitializingFieldsTest test = new InitializingFieldsTest();
    18     System.out.println(test.age); // 24
    19     System.out.println(test.flag); // true
    20   }
    21 }

      The Java compiler copies initializer blocks into every constructor.

      Therefore, this approach can be used to share a block of code between multiple constructors.

    reference from: https://docs.oracle.com/javase/tutorial/java/javaOO/initial.html

  • 相关阅读:
    JavaScript Basic Memo
    移动端WEB开发备忘录
    重学前端
    roadhog 构建优化
    ES6 memo
    styled-components 背后的魔法
    怎么在多场景下使用不同的 git 账号 commit
    三方登录总结
    Promise 错误处理
    观察者模式 vs 发布-订阅模式
  • 原文地址:https://www.cnblogs.com/yangwu-183/p/13491151.html
Copyright © 2011-2022 走看看