Java Reference
In-Depth Information
Listing 16-34. A FHidingSub3 Class That Demonstrates How to Access Hidden Fields of Superclass Using the super
Keyword
// FHidingSub3.java
package com.jdojo.inheritance;
public class FHidingSub3 extends FHidingSuper {
// Hides the num field in FHidingSuper class
private int num = 200;
// Hides the name field in FHidingSuper class
private String name = "Wally Inman";
public void print() {
// FHidingSub3.num
System.out.println("num: " + num);
// FHidingSuper.num
System.out.println("super.num: " + super.num);
// FHidingSub3.name
System.out.println("name: " + name);
// FHidingSuper.name
System.out.println("super.name: " + super.name);
}
}
Listing 16-35. A Test Class That Accesses Hidden Fields
// FHidingTest3.java
package com.jdojo.inheritance;
public class FHidingTest3 {
public static void main(String[] args) {
FHidingSub3 fhSub3 = new FHidingSub3();
fhSub3.print();
}
}
num: 200
super.num: 100
name: Wally Inman
super.name: John Jacobs
Recall that when an object is created, the Java runtime allocates memory for all instance variables in the class of
the object and all of its ancestors. When you create an object of the FHidingSub2 or FHidingSub3 .class, memory will
be allocated for the four instance variables as shown in Figure 16-4 .
 
 
Search WWH ::




Custom Search