class B
{
static int a = 0;
{
System.out.println("B.scope is running");
a = 10 ;
}
static
{
System.out.println("B.static scope is running");
a = 20;
}
public B()
{
System.out.println("B.Constructor is running");
}
public static void main(String arg[])
{
System.out.println(B.a);
System.out.println(B.a);
B b1 = new B();
B b2 = new B();
System.out.println(b1.a);
System.out.println(b2.a);
class B
{
static int a = 0;
{
System.out.println("B.scope is running");
a = 10 ;
}
static
{
System.out.println("B.static scope is running");
a = 20;
}
public B()
{
a = 30;
System.out.println("B.Constructor is running");
}
public static void main(String arg[])
{
System.out.println(B.a);
System.out.println(B.a);
B b1 = new B();
B b2 = new B();
System.out.println(b1.a);
System.out.println(b2.a);
System.out.println(B.a);
}
}
运行结果为:
B.static scope is running
20
20
B.scope is running
B.Constructor is running
B.scope is running
B.Constructor is running
30
30
30
class B
{
static int a = 0;
{
System.out.println("B.scope is running");
a = 10 ;
}
static
{
System.out.println("B.static scope is running");
a = 20;
}
public B()
{
a = 30;
System.out.println("B.Constructor is running");
}
/*
public static void main(String arg[])
{
System.out.println(B.a);
System.out.println(B.a);
B b1 = new B();
B b2 = new B();
System.out.println(b1.a);
System.out.println(b2.a);
System.out.println(B.a);
}
*/
}
class C extends B
{
static int c = 0;
static
{
c = 10;
System.out.println("C.static code is runnning and now c is " + c);
}
{
c = 20;
System.out.println("C.non-static code is runnning and now c is " + c);
}
public C()
{
c = 30;
System.out.println("C.constructor is running and now c is " + c);
}
public static void main(String args[])
{
System.out.println(C.c);
System.out.println(C.c);
C c1 = new C();
C c2 = new C();
System.out.println(c1.c);
System.out.println(c2.c);
System.out.println(C.c);
B.static scope is running
C.static code is runnning and now c is 10
10
10
B.scope is running
B.Constructor is running
C.non-static code is runnning and now c is 20
C.constructor is running and now c is 30
B.scope is running
B.Constructor is running
C.non-static code is runnning and now c is 20
C.constructor is running and now c is 30
30
30
30