Classes become useful when they work together to build more complex functionality. Java classes often contain references to other classes. The fields and methods of these referenced classes are accessed using the standard dot notation used in most OOP languages. If a Circle class has a borderColor field and a getArea() method that are publicly accessible, another class with a Circle instance named myCircle could access them as shown in the following: myCircle.borderColor = Color.blue; double area = myCircle.getArea(); You have seen how to refer to other classes but how does a class refer to itself? Although the reasons to do so might not seem so obvious at first, self-reference by a class is an important capability. In general, there are three situations where this need arises:
Self-reference within a class is supported by the this keyword. In addition to the preceding uses for this, you also saw its use previously when calling one constructor from another. Here's an example of a common use for this in distinguishing a field named width from a parameter with the same name: public void setWidth(int width) { this.width = width; } |