Java Reference
In-Depth Information
the field z in class H hides the field z in class G . The simple names of fields x , y , and z in class H refer to the hiding fields,
not inherited fields. Therefore, if you use the simple name x in class H , it refers to the field x declared in class H , not in
class G . If you want to refer to the field x in class G from inside class H , you need to use the keyword super , for example,
super.x .
In Listing 16-29, the FHidingSuper class declares fields num and name . In Listing 16-30, the FHidingSub class
inherits from the FHidingSuper class and it inherits the num and name fields from it. The print() method of the
FHidingSub class prints the values of the num and name fields. The print() method uses simple names of num and
name fields and they refer to the inherited fields from the FHidingSuper class. When you run the FHidingTest class in
Listing 16-31, the output shows that the FHidingSub class really inherits num and name fields from its superclass.
Listing 16-29. FHidingSuper Class with Two Protected Instance Fields
// FHidingSuper.java
package com.jdojo.inheritance;
public class FHidingSuper {
protected int num = 100;
protected String name = "John Jacobs";
}
Listing 16-30. FHidingSub Class, Which Inherits from the FHidingSuper Class and Inherits Fields num and name
// FHidingSub.java
package com.jdojo.inheritance;
public class FHidingSub extends FHidingSuper {
public void print() {
System.out.println("num: " + num);
System.out.println("name: " + name);
}
}
Listing 16-31. A Test Class to Demonstrate field's Inheritances
// FHidingTest.java
package com.jdojo.inheritance;
public class FHidingTest {
public static void main(String[] args) {
FHidingSub fhSub = new FHidingSub();
fhSub.print();
}
}
num: 100
name: John Jacobs
Let's consider the definition of class FHidingSub2 listed in Listing 16-32.
 
Search WWH ::




Custom Search