Java Reference
In-Depth Information
FHidingSuper sup = new FHidingSuper( );
FHidingSub2 sub = new FHidingSub2( );
num
name
num
name
num
name
FHidingSub2
part of
instance variables
FHidingSuper
part of
instance variables
Figure 16-4.
Memory layout for objects of FHidingSuper and FHidingSub2 classes
Let's summarize the field hiding rules:
•
Field hiding occurs when a class declares a variable with the same name as an inherited
variable from its superclass.
•
Field hiding occurs only based on the name of the field. Access level, data type, and the type
of field (
static
or non-static) are not considered for field hiding. For example, a
static
field
can hide an instance field. A field of
int
type can hide a field of
String
type, etc. A
private
field in a class can hide a
protected
field in its superclass. A
public
field in a class can hide a
protected
field in its superclass.
super
to access the hidden fields of the superclass. The class
can use the simple names to access the redefined fields in its body.
•
A class should use the keyword
Disabling Inheritance
You can disable subclassing for a class by declaring the class
final
. You have seen the use of the
final
keyword before
for declaring constants. The same
final
keyword is used in a class declaration. A
final
class cannot be subclassed.
The following snippet of code declares a
final
class named
Security
:
public final class Security {
// Code goes here
}
The following declaration of class
CrackedSecurity
will not compile:
// Won't compile. Cannot inherit from Security
public final class CrackedSecurity extends Security {
// Code goes here
}
You can also declare a method as
final
. A
final
method cannot be overridden or hidden by a subclass. Since
a
final
method cannot be overridden or hidden, a call to a
final
method may be inlined by a code optimizer for
better performance.