Object :
The reference values (often just references) are pointers to these objects, and a special null reference, which refers to no object.
Object Creation
class Point { int x, y; Point() { System.out.println("default"); } Point(int x, int y) { this.x = x; this.y = y; } /* A Point instance is explicitly created at class initialization time: */ static Point origin = new Point(0,0); /* A String can be implicitly created by a + operator: */ public String toString() { return "(" + x + "," + y + ")"; } } class Test { public static void main(String[] args) { /* A Point is explicitly created using newInstance: */ Point p = null; try { p = (Point)Class.forName("Point").newInstance(); } catch (Exception e) { System.out.println(e); } /* An array is implicitly created by an array constructor: */ Point a[] = { new Point(0,0), new Point(1,1) }; /* Strings are implicitly created by + operators: */ System.out.println("p: " + p); System.out.println("a: { " + a[0] + ", " + a[1] + " }"); /* An array is explicitly created by an array creation expression: */ String sa[] = new String[2]; sa[0] = "he"; sa[1] = "llo"; System.out.println(sa[0] + sa[1]); } }
This program produces the output:
default p: (0,0) a: { (0,0), (1,1) } hello
- The string concatenation operator
+
, which, when given aString
operand and a reference, will convert the reference to aString
by invoking theto String
method of the referenced object (using"null"
if either the reference or the result ofto String
is a null reference), and then will produce a newly createdString
that is the concatenation of the two strings
There may be many references to the same object. Most objects have state, stored in the fields of objects that are instances of classes or in the variables that are the components of an array object. If two variables contain references to the same object, the state of the object can be modified using one variable's reference to the object, and then the altered state can be observed through the reference in the other variable.
No comments:
Post a Comment