15.10.2
Accessing Superclass Members using
super
EXPRESSIONS
t.z()=1 when t holds a class T at run time.
s.z()=0 when s holds a class S at run time.
s.z()=1 when s holds a class T at run time.
The last line shows that, indeed, the method that is accessed
does
depend on the
run time class of referenced object; when
s
holds a reference to an object of class
T
, the expression
s.z()
refers to the
z
method of class
T
, despite the fact that the
type of the expression
s
is
S
. Method
z
of class
T
overrides method
z
of class
S
.
The following example demonstrates that a null reference may be used to
access a class (
static
) variable without causing an exception:
class Test {
static String mountain = "Chocorua";
static Test favorite(){
System.out.print("Mount ");
return null;
}
public static void main(String[] args) {
System.out.println(favorite().mountain);
}
}
It compiles, executes, and prints:
Mount Chocorua
Even though the result of
favorite()
is
null
, a
NullPointerException
is
not
thrown. That
Mount
is printed demonstrates that the
Primary
expression is
indeed fully evaluated at run time, despite the fact that only its type, not its value,
is used to determine which field to access (because the field
mountain
is
static
).
15.10.2 Accessing Superclass Members using
super
The special form using the keyword
super
is valid only in an instance method or
constructor, or in the initializer of an instance variable of a class; these are exactly
the same situations in which the keyword
this
may be used ( 15.7.2). The form
involving
super
may not be used anywhere in the class
Object
, since
Object
has
no superclass; if
super
appears in class
Object
, then a compile time error results.
Suppose that a field access expression
super.name
appears within class
C
,
and the immediate superclass of
C
is class
S
. Then
super.name
is treated exactly
as if it had been the expression
((S)this).name
; thus, it refers to the field
named
name
of the current object, but with the current object viewed as an
instance of the superclass. Thus it can access the field named
name
that is visible
322
footer
Our partners:
PHP: Hypertext Preprocessor Best Web Hosting
Java Web Hosting
Inexpensive Web Hosting
Jsp Web Hosting
Cheapest Web Hosting
Jsp Hosting
Cheap Hosting
Visionwebhosting.net Business web hosting division of Web
Design Plus. All rights reserved