课程: Learning Java 17

Instance versus class members - Java教程

课程: Learning Java 17

Instance versus class members

- [Instructor] Let's calculate the area of each triangle using the findArea method. We'll store the area of triangleA in a variable. It'll be a double, because that's what the findArea function returns. To access the findArea function, we'll use the dot operation on the triangleA instance. We'll write, triangleA findArea. Now you might be thinking, why didn't we write triangle findArea? Isn't that what we did when we used pow from the Math class with Math.pow? And yes, this is a where a lot of people get confused. The reason we did triangleA.findArea instead of triangle.findArea is because in order to find the area of a given triangle you have to have a triangle instance. You can't calculate the area of a triangle that doesn't exist. The implementation of findArea relies on the attribute values of a given triangle. The base might be eight or 10 or 15, we don't know until the triangles actually create it. Because we have to have a triangle instance already created to use the findArea method, we can say findArea is an instance method. For Math.pow, we did not need to create an instance of Math in order to use the pow function. We just accessed the class and used the function we wanted. That's because pow is not an instance method, it's a class method because you do not need to create an instance of the Math class in order to use the function. Because of this instance methods are often referred to as non-static methods, since you have to create an instance in order to use them. You do not need an instance created to use a class method or often called a static method. You can just reference the class. We've actually already used instance methods earlier in this course. We used charAt with a string. This retrieved a character at a certain index in the string. In order to use this function, a string already needed to be created. Otherwise, what character would we retrieve? In our code from earlier, we wrote, studentFirstName.charAt(0) and studentLastName.charAt(0). Both student first name and student last name evaluated to string values. For each of these we used the dot operator on an instance of a String in order to get access to the charAt method. Because we used the dot operator on an instance and not on the class name, charAt is an instance method and not a class method. Understanding the differences between instance method and class methods is very important as you continue to learn Java.

内容