对static关键字的用法还是不是很理解,在think in java中有这么一段代码class Bowl
{
Bowl(int er)
{
System.out.println("Bowl(" + er + ")");
}
void f1(int er)
{
System.out.println("f1(" + er + ")");
}
}
class Table
{
static Bowl bowl1 = new Bowl(1);
Table()
{
System.out.println("Table()");
bowl2.f1(1);
}
void f2(int er)
{
System.out.println("f2(" + er + ")");
}
static Bowl bowl2 = new Bowl(2);
}
class Cupboard
{
Bowl bowl3 = new Bowl(3);
static Bowl bowl4 = new Bowl(4);
Cupboard()
{
System.out.println("Cupboard()");
bowl4.f1(2);
}
void f3(int er)
{
System.out.println("f3(" + er + ")");
}
static Bowl bowl5 = new Bowl(5);
}
public class StaticInitialization
{
public static void main(String[] args)
{
System.out.println("Creating new Cupboard() in main");
new Cupboard();
System.out.println("Creating new Cupboard() in main");
new Cupboard();
table.f2(1);
cupboard.f3(1);
}
static Table table = new Table();
static Cupboard cupboard = new Cupboard();
}
这样可以编译执行,但是我把public class里面的最后两条语句static Table table = new Table();
static Cupboard cupboard = new Cupboard();放在main方法里就不行了,希望老师们给予解答
{
Bowl(int er)
{
System.out.println("Bowl(" + er + ")");
}
void f1(int er)
{
System.out.println("f1(" + er + ")");
}
}
class Table
{
static Bowl bowl1 = new Bowl(1);
Table()
{
System.out.println("Table()");
bowl2.f1(1);
}
void f2(int er)
{
System.out.println("f2(" + er + ")");
}
static Bowl bowl2 = new Bowl(2);
}
class Cupboard
{
Bowl bowl3 = new Bowl(3);
static Bowl bowl4 = new Bowl(4);
Cupboard()
{
System.out.println("Cupboard()");
bowl4.f1(2);
}
void f3(int er)
{
System.out.println("f3(" + er + ")");
}
static Bowl bowl5 = new Bowl(5);
}
public class StaticInitialization
{
public static void main(String[] args)
{
System.out.println("Creating new Cupboard() in main");
new Cupboard();
System.out.println("Creating new Cupboard() in main");
new Cupboard();
table.f2(1);
cupboard.f3(1);
}
static Table table = new Table();
static Cupboard cupboard = new Cupboard();
}
这样可以编译执行,但是我把public class里面的最后两条语句static Table table = new Table();
static Cupboard cupboard = new Cupboard();放在main方法里就不行了,希望老师们给予解答
静态修饰符,什么叫静态修饰符呢?大家都知道,在程序中任何变量或者代码都是在编译时由系统自动分配内存来存储的,而所谓静态就是指在编译后所分配的内存会一直存在,直到程序退出内存才会释放这个空间,也就是只要程序在运行,那么这块内存就会一直存在。这样做有什么意义呢?
在Java程序里面,所有的东西都是对象,而对象的抽象就是类,对于一个类而言,如果要使用他的成员,那么普通情况下必须先实例化对象后,通过对象的引用才能够访问这些成员,但是有种情况例外,就是该成员是用static声明的(在这里所讲排除了类的访问控制)
static 属性可以被static和非static类型的方法使用
非static属性不能够被static方法所使用静态变量与静态方法类似。所有此类实例共享此静态变量,也就是说在类装载时,只分配一块存储空间static变量有点类似于C中的全局变量的概念