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);
}
}
|