Java Quick Reference
  Language Fundamentals
  Operators and Assignments
  Flow Control and Exceptions
  Declarations and Access Control
  Garbage Collection
  Overloading and Overriding
  Threads
  The java.lang Package
  The java.util Package
  The java.awt Package
  The java.io Package
  References
  Miscellaneous Notes
  Tips & Traps
  Mock Exams

Overloading, Overriding, Runtime Types and Object Orientation - Field Variables

  • consider the following scenario:
    1. Super has a field 'i' and a method test() which displays 'i'
    2. Sub is a subclass of Super with it's own field 'i' and method test()
    3. Super calls the test() method in it's constructor
  • Which value for 'i' will be displayed when a Sub object is instantiated?
  • Answer: the default value of the field 'i' in Sub
  • the subclass object is instantiated as follows:
    the Superclass constructor is called
    the Subclass method test() is used
    as the Subclass has not been fully initialized, 
       the default value of it's field variable is displayed
    the Subclass variables are initialized
    the Subclass constructor is called
  • When an overridden method is called from a superclass constructor both the Subclass method and field variables are used
  • Which methods and variables are used when an object reference for a Superclass is created and the assigned object is a Subclass type?
  • Answer: both the Subclass methods and variables are used. The declared type is only valid at compile-time. The actual object type is used at runtime.
  • BUT
  • if you access the field variable directly, ie not through a method, the variable for the declared type is returned.
Creating a Super objref and pointing it to Sub obj
  // subclass obj stored in super reference
  Super sp1 = sb;             
  
  // field variable in Sub object
  test() in Sub uses i: 20.0  
  
  // field variable in Super object
  sp1.i 10                    

Example Code

Encapsulation Polymorphism isA/hasA Overloading Overriding Field Variables
Initialization Top-level Classes Inner Classes Static Nested Classes Local Classes Anonymous Classes