官术网_书友最值得收藏!

Creating instances of classes and understanding their scope

We will write a few lines of code that create an instance of the Rectangle class named rectangle within the scope of a getGeneratedRectangleHeight method. The code within the method uses the created instance to access and return the value of its height field. In this case, the code uses the final keyword as a prefix to the Rectangle type to declare an immutable reference to the Rectangle instance named rectangle.

Note

An immutable reference is also known as a constant reference because we cannot replace the reference held by the rectangle constant with another instance of Rectangle.

After we define the new method, we will call it and we will force a garbage collection. The code file for the sample is included in the java_9_oop_chapter_03_01 folder, in the example03_15.java file.

double getGeneratedRectangleHeight() {
    final Rectangle rectangle = new Rectangle(37, 87);
    return rectangle.height; 
}

System.out.printf("Height: %.2f\n", getGeneratedRectangleHeight());
System.gc();

The following screenshot shows the results of executing the previous lines in JShell. We will see the messages that indicate that the finalize method for the instance has been called after the call to the getGeneratedRectangleHeight method and the next call to force the garbage collection. When the method returns a value, rectangle becomes out of scope because its reference count goes down from one to zero.

The instanced reference by immutable variable is safe for garbage collection. Thus, when we force the garbage collection, we see the message displayed by the finalize method.

主站蜘蛛池模板: 江陵县| 蒲城县| 黄平县| 苍山县| 黑河市| 肃宁县| 葫芦岛市| 宜兴市| 定州市| 合阳县| 夏津县| 呼伦贝尔市| 阿荣旗| 黄大仙区| 会宁县| 开封县| 璧山县| 伊宁市| 林甸县| 潍坊市| 石棉县| 石河子市| 铁岭县| 平阴县| 彭州市| 上思县| 丘北县| 邛崃市| 台东市| 天镇县| 巫溪县| 株洲县| 佛冈县| 衡阳市| 尉氏县| 准格尔旗| 天气| 武乡县| 乐业县| 栾城县| 海淀区|