THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

protected String name() {
return "More";
}


protected void printName() {
Base sref = (Base) this;


System.out.println("this.name() = " + this.name());
System.out.println("sref.name() = " + sref.name());
System.out.println("super.name() = " + super.name());
}
}


Although sref and super both refer to the same object using the type Base, only super will ignore the
real class of the object to use the superclass's implementation of name. The reference sref will act the same
way this acts, selecting an implementation of name based on the actual class of the object. Here is the
output of printName:


this.name() = More
sref.name() = More
super.name() = Base


3.4. Type Compatibility and Conversion


The Java programming language is strongly typed, which means that it checks for type compatibility at
compile time in most casespreventing incompatible assignments by forbidding anything questionable. Now
that you understand the basic type relationship defined by subclasses and superclasses, we can revisit a few
details regarding the compatibility of reference types within assignments (implicit or explicit) and conversion
between types. The full rules for how and when type conversions are applied, for both reference and primitive
types, are discussed in "Type Conversions" on page 216.


3.4.1. Compatibility


When you assign the value of an expression to a variable, either as part of an initializer, assignment statement,
or implicitly when an argument value is assigned to a method parameter, the type of the expression must be
compatible with the type of the variable. For reference types this means that the type of the expression must
be the same type as, or a subtype of, the declared type of the variableor can be converted to such a type. For
example, any method that expects an Attr object as a parameter will accept a ColorAttr object because
ColorAttr is a subtype of Attr. This is called assignment compatibility.[2] But the converse is not trueyou
cannot assign an Attr object to a variable of type ColorAttr, or pass an Attr object as an argument
when a ColorAttr is expected.


[2] There is a slight difference between direct assignment and parameter passingsee the
discussion on page 218.

The same rule applies for the expression used on a return statement within a method. The type of the
expression must be assignment compatible with the declared return type of the method.


The null object reference is a special case in that it is assignment compatible with all reference types,
including array typesa reference variable of any type can be assigned null.

Free download pdf