Java Reference
In-Depth Information
// Methods to operate on the instance field
public double area () { return PI * r * r ; }
public double circumference () { return 2 * PI * r ; }
}
We have defined the Circle class within a package named shapes . Because r is pro
tected , any other classes in the shapes package have direct access to that field and
can set it however they like. The assumption here is that all classes within the
shapes package were written by the same author or a closely cooperating group of
authors and that the classes all trust each other not to abuse their privileged level of
access to each other's implementation details.
Finally, the code that enforces the restriction against negative radius values is itself
placed within a protected method, checkRadius() . Although users of the Circle
class cannot call this method, subclasses of the class can call it and even override it if
they want to change the restrictions on the radius.
It is a common convention in Java that data accessor methods
begin with the prefixes “get” and “set.” But if the field being
accessed is of type boolean , the get() method may be
replaced with an equivalent method that begins with “is.” For
example, the accessor method for a boolean field named read
able
is
typically
called
isReadable()
instead
of
getReadable() .
Abstract Classes and Methods
In Example 3-4 , we declared our Circle class to be part of a package named shapes .
Suppose we plan to implement a number of shape classes: Rectangle , Square ,
Ellipse , Triangle , and so on. We can give these shape classes our two basic area()
and circumference() methods. Now, to make it easy to work with an array of
shapes, it would be helpful if all our shape classes had a common superclass, Shape .
If we structure our class hierarchy this way, every shape object, regardless of the
actual type of shape it represents, can be assigned to variables, fields, or array ele‐
ments of type Shape . We want the Shape class to encapsulate whatever features all
our shapes have in common (e.g., the area() and circumference() methods). But
our generic Shape class doesn't represent any real kind of shape, so it cannot define
useful implementations of the methods. Java handles this situation with abstract
methods .
Java lets us define a method without implementing it by declaring the method with
the abstract modifier. An abstract method has no body; it simply has a signature
Search WWH ::




Custom Search