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

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.

主站蜘蛛池模板: 宁蒗| 顺昌县| 中西区| 达孜县| 宁夏| 马鞍山市| 民丰县| 涞水县| 乌拉特中旗| 宁明县| 涟源市| 闽清县| 北流市| 双桥区| 东方市| 东方市| 岳西县| 金乡县| 蒙城县| 连城县| 南皮县| 龙州县| 庄河市| 玉环县| 石门县| 崇礼县| 明星| 赫章县| 成武县| 视频| 利津县| 沙雅县| 沛县| 鹤庆县| 铁岭市| 莲花县| 枝江市| 札达县| 博野县| 营口市| 新野县|