4.5.5
Variables Have Types, Objects Have Classes
TYPES, VALUES, AND VARIABLES
that is not
null
, it refers to an object or array that has a class (not a type), and that
class will necessarily be compatible with the compile time type.
Even though a variable or expression may have a compile time type that is an
interface type, there are no instances of interfaces. A variable or expression whose
type is an interface type can reference any object whose class implements ( 8.1.4)
that interface.
Here is an example of creating new objects and of the distinction between the
type of a variable and the class of an object:
public interface Colorable {
void setColor(byte r, byte g, byte b);
}
class Point { int x, y; }
class ColoredPoint extends Point implements Colorable {
byte r, g, b;
public void setColor(byte rv, byte gv, byte bv) {
r = rv; g = gv; b = bv;
}
}
class Test {
public static void main(String[] args) {
Point p = new Point();
ColoredPoint cp = new ColoredPoint();
p = cp;
Colorable c = cp;
}
}
In this example:
The local variable
p
 of the method
main
 of class
Test
 has type
Point
 and is
initially assigned a reference to a new instance of class
Point
.
The local variable
cp
 similarly has as its type
ColoredPoint
, and is initially
assigned a reference to a new instance of class
ColoredPoint
.
The assignment of the value of
cp
 to the variable
p
 causes
p
 to hold a refer 
ence to a
ColoredPoint
 object. This is permitted because
ColoredPoint
 is a
subclass of
Point
, so the class
ColoredPoint
 is assignment compatible
( 5.2) with the type
Point
. A
ColoredPoint
 object includes support for all
the methods of a
Point
. In addition to its particular fields
r
,
g
, and
b
, it has
the fields of class
Point
, namely
x
 and
y
.
48






footer




 

 

 

 

 Home | About Us | Network | Services | Support | FAQ | Control Panel | Order Online | Sitemap | Contact

java hosting

 

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