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

  • Java 9 with JShell
  • Gastón C. Hillar
  • 250字
  • 2021-07-09 18:46:50

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.

主站蜘蛛池模板: 长泰县| 台中县| 南投市| 张家川| 安康市| 普宁市| 鹤峰县| 甘肃省| 宁远县| 东港市| 揭东县| 惠东县| 永德县| 石狮市| 沙湾县| 将乐县| 岚皋县| 澳门| 新建县| 微山县| 潞城市| 蓬安县| 长垣县| 惠州市| 清苑县| 宁陵县| 彰化县| 闸北区| 崇信县| 常州市| 湛江市| 玉树县| 莱州市| 金昌市| 大宁县| 准格尔旗| 安福县| 湖北省| 祁门县| 名山县| 阿拉尔市|