- Java 9 Programming By Example
- Peter Verhas
- 229字
- 2021-07-02 23:37:36
Object initializers and constructors
When an object is instantiated, the appropriate constructor is called. The constructor declaration looks like a method with the following deviation: the constructor does not have a return value. That is because the constructors work on the not-fully-ready instance when the new command operator is invoked and does not return anything. Constructors, having the same name as the class, cannot be distinguished from each other. If there is a need for more than one constructor, they have to be overloaded. Constructors, thus, can call each other, almost as if they were void methods with different arguments. However, there is a restriction—when a constructor calls another, it has to be the very first instruction in the constructor. You use this() syntax with an appropriate argument list, which may be empty, to invoke a constructor from another constructor.
The initialization of the object instance also executes initializer blocks. These are blocks containing executable code inside the { and } characters outside the methods and constructors. They are executed before the constructor in the order they appear in the code, together with the initialization of the fields in case their declarations contain value initialization.
If you see the static keyword in front of an initializer block, the block belongs to the class and is executed when the class is loaded along with the static field initializers.
- C++程序設(shè)計(jì)教程
- Data Visualization with D3 4.x Cookbook(Second Edition)
- Spring 5.0 Microservices(Second Edition)
- 大學(xué)計(jì)算機(jī)基礎(chǔ)(第三版)
- Visual Basic程序設(shè)計(jì)教程
- TypeScript圖形渲染實(shí)戰(zhàn):基于WebGL的3D架構(gòu)與實(shí)現(xiàn)
- Mastering Swift 2
- 算法訓(xùn)練營:提高篇(全彩版)
- Java程序設(shè)計(jì)
- 低代碼平臺(tái)開發(fā)實(shí)踐:基于React
- Quantum Computing and Blockchain in Business
- iPhone應(yīng)用開發(fā)從入門到精通
- Clojure for Java Developers
- Learning Concurrency in Python
- Mastering Leap Motion