Referring to Class Elements

   

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:

  • When a parameter or local variable in a method has the same name as a field of the class.

  • When a class needs to pass itself as an argument to a method.

  • When a class needs to return a reference to itself as the result of a method call. This is particularly helpful in building method calls that can be chained together as a single statement.

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; } 
   


Special Edition Using Java 2 Standard Edition
Special Edition Using Java 2, Standard Edition (Special Edition Using...)
ISBN: 0789724685
EAN: 2147483647
Year: 1999
Pages: 353

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net