public
class
TStatic {
static
int
i
;
public
TStatic() {
i
= 4;
}
public
TStatic(
int
j) {
i
= j;
}
public
static
void
main(String args[]) {
System.
out
.println(TStatic.
i
);
TStatic t =
new
TStatic(5);
//
声明对象引用,并实例化。此时
i=5
System.
out
.println(t.
i
);
TStatic tt =
new
TStatic();
//
声明对象引用,并实例化。此时
i=4
System.
out
.println(t.
i
);
System.
out
.println(tt.
i
);
System.
out
.println(t.
i
);
}
}
|
class
ClassA {
int
b
;
public
void
ex1() {}
class
ClassB {
void
ex2() {
int
i;
ClassA a =
new
ClassA();
i = a.
b
;
//
这里通过对象引用访问成员变量
b
a.ex1();
//
这里通过对象引用访问成员函数
ex1
}
}
}
|
class
ClassA {
static
int
b
;
static
void
ex1() {}
}
class
ClassB {
void
ex2() {
int
i;
i = ClassA.
b
;
//
这里通过类名访问成员变量
b
ClassA.ex1();
//
这里通过类名访问成员函数
ex1
}
}
|
public
class
StaticCls {
public
static
void
main(String[] args) {
OuterCls.InnerCls oi =
new
OuterCls.InnerCls();
//
这之前不需要
new
一个
OuterCls
}
}
class
OuterCls {
public
static
class
InnerCls {
InnerCls() {
System.
out
.println(
"InnerCls"
);
}
}
}
|
class
Value {
static
int
c
= 0;
Value() {
c
= 15;
}
Value(
int
i) {
c
= i;
}
static
void
inc() {
c
++;
}
}
class
Count {
public
static
void
prt(String s) {
System.
out
.println(s);
}
Value
v
=
new
Value(10);
static
Value
v1
,
v2
;
static
{
prt(
"in the static block of calss Count v1.c="
+
v1
.
c
+
" v2.c="
+
v2
.
c
);
v1
=
new
Value(27);
prt(
"in the static block of calss Count v1.c="
+
v1
.
c
+
" v2.c="
+
v2
.
c
);
v2
=
new
Value();
prt(
"in the static block of calss Count v1.c="
+
v1
.
c
+
" v2.c="
+
v2
.
c
);
}
}
public
class
TStaticBlock {
public
static
void
main(String[] args) {
Count ct =
new
Count();
Count.prt(
"in the main:"
);
Count.prt(
"ct.c="
+ ct.
v
.
c
);
Count.prt(
"v1.c="
+ Count.
v1
.
c
+
" v2.c="
+ Count.
v2
.
c
);
Count.
v1
.inc();
Count.prt(
"v1.c="
+ Count.
v1
.
c
+
" v2.c="
+ Count.
v2
.
c
);
Count.prt(
"ct.c="
+ ct.
v
.
c
);
}
}
|