, native, .
synchronized
, . synchronized, , . notifyAll(), notify() wait() Object ( Java) synchronized, .
. , , :
{ /* */ }
static { /* */ }
, . , , , . this, .
static. () .
/* # 7: :
Department.java: DemoLogic.java */
package chapt03;
public class Department {
{
System. out. println("logic (1) id=" + this. id);
}
static {
System. out. println("static logic");
}
private int id = 7;
public Department(int d) {
id = d;
System. out. println(" id=" + id);
}
int getId() {
return id;
}
{
id = 10;
System. out. println("logic (2) id=" + id);
}
}
package chapt03;
public class DemoLogic {
public static void main(String[] args) {
Department obj = new Department(71);
System. out. println(" id=" + obj.getId());
}
}
:
Static logic
logic (1) id=0
logic (2) id=10
id=71
id=71
id , , . id, 10, , .
, , . . . , . , .
|
|
.
, .
/* # 8: : NumberInfo.java */
package chapt04;
public class NumberInfo {
public static void viewNum(Integer i) { //1
System. out. printf("Integer=%d%n", i);
}
public static void viewNum(int i) { //2
System. out. printf("int=%d%n", i);
}
public static void viewNum(Float f) { //3
System. out. printf("Float=%.4f%n", f);
}
public static void viewNum(Number n) { //4
System. out. println("Number=" + n);
}
public static void main(String[] args) {
Number[] num =
{ new Integer(7), 71, 3.14f, 7.2 };
for (Number n: num)
viewNum (n);
viewNum (new Integer(8));
viewNum (81);
viewNum (4.14f);
viewNum (8.2);
}
}
, , :
Number=7
Number=71
Number=3.14
Number=7.2
Integer=8
int=81
Float=4,1400
Number=8.2
. , num. , ( ), , .
.
, , , , .
:
;
;
.
J2SE 5 (generic) , , . generic- . , , .
generic- :
/* # 9: : Subject.java */
package chapt03;
public class Subject <T1, T2> {
|
|
private T1 name;
private T2 id;
public Subject() {
}
public Subject(T2 ids, T1 names) {
id = ids;
name = names;
}
}
T1, 2 , . . .
Subject , , :
Subject<String,Integer> sub =
new Subject<String,Integer>();
char ch[] = {'J','a','v','a'};
Subject<char[],Double> sub2 =
new Subject<char[],Double>(ch, 71D);
sub2 71D Double.
.
Optional , .
/* # 10:
: Optional.java: Runner.java */
package chapt03;
public class Optional <T> {
private T value;
public Optional() {
}
public Optional(T value) {
this. value = value;
}
public T getValue() {
return value;
}
public void setValue(T val) {
value = val;
}
public String toString() {
if (value == null) return null;
return value.getClass().getName() + " " + value;
}
}
package chapt03;
public class Runner {
public static void main(String[] args) {
// Integer
Optional<Integer> ob1 =
new Optional<Integer>();
ob1.setValue(1);
//ob1.setValue("2");// :
int v1 = ob1.getValue();
System. out. println(v1);
// String
Optional<String> ob2 =
new Optional<String>("Java");
String v2 = ob2.getValue();
System. out. println(v2);
//ob1 = ob2; //
// Object
Optional ob3 = new Optional();
System. out. println(ob3.getValue());
ob3.setValue("Java SE 6");
System. out. println(ob3.toString()); /*
, */
ob3.setValue(71);
System. out. println(ob3.toString());
ob3.setValue(null);
}
}
:
Java
Null