Java Reference
In-Depth Information
Listing 16-32.
A FHidingSub2 Class That Inherits from FHidingSuper and Declares Two Variables with the Same
Name as Declared in Its Superclass
// FHidingSub2.java
package com.jdojo.inheritance;
public class FHidingSub2 extends FHidingSuper {
// Hides num field in FHidingSuper class
private int num = 200;
// Hides name field in FHidingSuper class
private String name = "Wally Inman";
public void print() {
System.out.println("num: " + num);
System.out.println("name: " + name);
}
}
The
FHidingSub2
class inherits from the
FHidingSuper
class. It declares two fields
num
and
name
, which have
the same names as the two fields declared in its superclass. This is a case of field hiding. The
num
and
name
fields in
FHidingSub2
hide the
num
and
name
fields that are inherited from the
FHidingSuper
class. When the
num
and
name
fields are used by their simple names inside the
FHidingSub2
class, they refer to the fields declared in the
FHidingSub2
class, not to the inherited fields from the
FHidingSuper
class. This is verified by running the
FHidingTest2
class as
listed in Listing 16-33.
Listing 16-33.
A Test Class to Demonstrate Field Hiding
// FHidingTest2.java
package com.jdojo.inheritance;
public class FHidingTest2 {
public static void main(String[] args) {
FHidingSub2 fhSub2 = new FHidingSub2();
fhSub2.print();
}
}
num: 200
name: Wally Inman
The
FHidingSub2
class has four fields, two inherited (
num
and
name
) and two declared (
num
and
name
). If you want
to refer to the inherited fields from the superclass, you need to qualify the field names with the keyword
super
. For
example,
super.num
and
super.name
inside
FHidingSub2
refers to the
num
and
name
fields in
FHidingSuper
class.
The
print()
method of the
FHidingSub3
class in Listing 16-34 uses the keyword
super
to access hidden fields of
the superclass and uses the simple names of the fields to access fields from its own class. The output of Listing 16-35
verifies this.