Java Reference
In-Depth Information
Top of Stack
Space for n = 1
Dynamic Link
Return Value = 1
Frame Pointer
Space for n = 2
Dynamic Link
Return Value
Space for n = 3
Dynamic Link = Null
Return Value
Figure 12.4: Runtime Stack for a Call of fact(3)with Dynamic Links
tiple scopes. Java, C
, for example, allow classes to have member
functions that have direct access to all instance variables. Consider the follow-
ing Java class:
++
,andC
class k {
int a;
int sum(){
int b = 42;
return a+b;
}}
Each object that is an instance of class k contains a member function sum.
Only one translation of sum is created; it is shared by all instances of k.When
sum executes, it requires two pointers to access local and object-level data.
Local data, as usual, resides in a frame on the runtime stack. Data values for a
particular instance of k are accessed through an object pointer (called the this
pointer in Java, C
). When obj.sum() is called, it is given an extra
implicit parameter that is a pointer to obj. This is illustrated in Figure 12.5.
When a+b is computed, b, a local variable, is accessed directly through the
frame pointer. a, a member of object obj, is accessed indirectly through the
object pointer that is stored in the frame (as all parameters to a method are).
C
++
,andC
, and Java also allow inheritance via subclassing .Thatis,anew
class can extend an existing class, adding new fields and adding or redefining
methods. A subclass D,ofclassC, may be be used in contexts expecting an
object of class C (e.g., inmethod calls). This is supported rather easily; instances
of class D always contain an instance of C within them. That is, if C has a field F
within it, so does D.ThefieldsD declares aremerely appended at the end of the
allocations for C. As a result, access to fields declared in C within an instance
of D works perfectly. In Java, class Object is often used as a placeholder when
an object of unknown type is expected. This works because all Java classes are
,C
++
 
Search WWH ::




Custom Search