Java Reference
In-Depth Information
The definition of the
isInside()
method shows field inheritance; this method uses
the field
r
(defined by the
Circle
class) as if it were defined right in
PlaneCircle
itself.
PlaneCircle
also inherits the methods of
Circle
. Therefore, if we have a
Pla
neCircle
object referenced by variable
pc
, we can say:
double
ratio
=
pc
.
circumference
()
/
pc
.
area
();
This works just as if the
area()
and
circumference()
methods were defined in
PlaneCircle
itself.
Another feature of subclassing is that every
PlaneCircle
object is also a perfectly
legal
Circle
object. If
pc
refers to a
PlaneCircle
object, we can assign it to a
Circle
variable and forget all about its extra positioning capabilities:
// Unit circle at the origin
PlaneCircle
pc
=
new
PlaneCircle
(
1.0
,
0.0
,
0.0
);
Circle
c
=
pc
;
// Assigned to a Circle variable without casting
This assignment of a
PlaneCircle
object to a
Circle
variable can be done without a
cast. As we discussed in
Chapter 2
a conversion like this is always legal. The value
held in the
Circle
variable
c
is still a valid
PlaneCircle
object, but the compiler
cannot know this for sure, so it doesn't allow us to do the opposite (narrowing) con‐
version without a cast:
// Narrowing conversions require a cast (and a runtime check by the VM)
PlaneCircle
pc2
=
(
PlaneCircle
)
c
;
boolean
origininside
=
((
PlaneCircle
)
c
).
isInside
(
0.0
,
0.0
);
This distinction is covered in more detail in
“Lambda Expressions” on page 171
,
where we talk about the distinction between the compile and runtime type of an
object.
Final classes
When a class is declared with the
final
modifier, it means that it cannot be exten‐
ded or subclassed.
java.lang.String
is an example of a
final
class. Declaring a
class
final
prevents unwanted extensions to the class: if you invoke a method on a
String
object, you know that the method is the one defined by the
String
class
itself, even if the
String
is passed to you from some unknown outside source.
Superclasses, Object, and the Class Hierarchy
In our example,
PlaneCircle
is a subclass of
Circle
. We can also say that
Circle
is
the superclass of
PlaneCircle
. The superclass of a class is specified in its
extends
clause:
public
class
PlaneCircle
extends
Circle
{
...
}
Every class you define has a superclass. If you do not specify the superclass with an
extends
clause, the superclass is the class
java.lang.Object
. The
Object
class is
special for a couple of reasons: