课程: Learning Java 17

Using instance and class methods in Java - Java教程

课程: Learning Java 17

Using instance and class methods in Java

- [Instructor] Let's get back to the triangle program. In the main function, we create two triangles. Then, we use the dot operator on triangleA to access the findArea function, so we can find the area of triangleA. Let's print it out. system.out.println and we'll print the area of triangleA. Let's add a break point to where we make the findArea call. We'll run it in debug mode. Here, we're about to call the findArea function on triangleA. In the variables window, we can see our triangleA instance and the triangleB instance. They each have their specific attribute values. Let's hit step into to step into this call. findArea. Now we're in the implementation. For triangleA, the base attribute has the value 15 and the height attribute has the value eight. We use the this keyword to access the base and height values of triangleA. Then, we use the formula, base times height divided by two, to calculate triangleA's specific area. Let's hit Continue and switch over to the console. We see 60. Eight times 15 divided by two is 60. We can find the area for triangleB as well. Of course, since triangleB has different attributes for the base and height, we'll get a different output for the area. Let's create a double variable called triangleBArea and we'll calculate the area of triangleB. We'll access triangleB and use the findArea function. findArea the instance method. Then, we'll display that area in the console. We'll also move our break point. We'll have it be at line 11. Let's run in debug mode. Here, we have triangleB. We're about to find the area. triangleA's area is 60 and we just saw how that was calculated. Let's step into findArea, but we'll step into triangleB's call of this function. This time around, triangleB has a base three and a height of 2.598. These are the values that will be used to calculate the area of triangleB. We use its attribute values. 60's already in the console, and if we hit Continue, we see 3.897. That's the base times the height divided by two for triangleB. With this program, we used the findArea instance method on two different triangle instances.

内容