10.12.2012 Views

The Java Language Specification, Third Edition

The Java Language Specification, Third Edition

The Java Language Specification, Third Edition

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

TYPES, VALUES, AND VARIABLES Objects 4.3.1<br />

<strong>The</strong> sample code:<br />

class Point { int[] metrics; }<br />

interface Move { void move(int deltax, int deltay); }<br />

declares a class type Point, an interface type Move, and uses an array type int[]<br />

(an array of int) to declare the field metrics of the class Point.<br />

4.3.1 Objects<br />

An object is a class instance or an array.<br />

<strong>The</strong> reference values (often just references) are pointers to these objects, and a<br />

special null reference, which refers to no object.<br />

A class instance is explicitly created by a class instance creation expression<br />

(§15.9). An array is explicitly created by an array creation expression (§15.10).<br />

A new class instance is implicitly created when the string concatenation operator<br />

+ (§15.18.1) is used in a non-constant (§15.28) expression, resulting in a new<br />

object of type String (§4.3.3). A new array object is implicitly created when an<br />

array initializer expression (§10.6) is evaluated; this can occur when a class or<br />

interface is initialized (§12.4), when a new instance of a class is created (§15.9),<br />

or when a local variable declaration statement is executed (§14.4). New objects of<br />

the types Boolean, Byte, Short, Character, Integer, Long, Float and Double may<br />

be implicitly created by boxing conversion (§5.1.7).<br />

Many of these cases are illustrated in the following example:<br />

class Point {<br />

int x, y;<br />

Point() { System.out.println("default"); }<br />

Point(int x, int y) { this.x = x; this.y = y; }<br />

// A Point instance is explicitly created at class initialization time:<br />

static Point origin = new Point(0,0);<br />

// A String can be implicitly created by a + operator:<br />

public String toString() {<br />

return "(" + x + "," + y + ")";<br />

}<br />

}<br />

class Test {<br />

public static void main(String[] args) {<br />

// A Point is explicitly created using newInstance:<br />

Point p = null;<br />

try {<br />

p = (Point)Class.forName("Point").newInstance();<br />

} catch (Exception e) {<br />

System.out.println(e);<br />

}<br />

DRAFT<br />

45

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!