您现在的位置是:首页
>
java封装关键字 Java 封装之static关键字
Java 封装之 tatic关键字 逐步深入的学习 都会发现主函数的修饰符中的 tatic关键字 亦或是在定义一个函数的时候 有mai 函数直接访问也会定义成 tatic void method
Java 封装之static关键字
逐步深入的学习 都会发现主函数的修饰符中的static关键字 亦或是在定义一个函数的时候 有main函数直接访问也会定义成static void method() 如下面的程序片段:
class Test { static void method(){ System out println( Function method() ); } public static void main(String[] args) { method(); //实际是: thod(); } }static关键字 用来修饰成员(成员变量和成员函数) 也成为类成员未被static修饰的又称为对象成员
被修饰后的成员具备以下特点:
< >随着类的加载而加载 随着类的消失而消亡
< >优先于对象存在
< >被所有对象所共享 凡是类的实例对象均可以调用静态成员
< >可以直接被类名调用 格式是: 类名 静态成员(变量或者方法) 类名也可以省略
注意事项
< >静态方法只能访问静态成员(变量和方法)
< >非静态方法可以访问静态成员(变量和方法) 也可以访问非静态成员
< >静态方法中不可以写this super关键字
(this super是和对象引用相关的关键字 是在对象被创建后才能够用来访问 而static成员则是优先于对象存在的 )
< >主函数main是静态的
< >静态代码块:
格式static{要执行的内容}
随着类的加载而加载 并且执行一次 且优先于主函数执行 用于给类进行初始化
static出现的时机
< >对象访问成员的时候出现大量的共同数据时候 该变量可以定义为静态的

< >若一个方法内部没有 非 静态数据(即是对象持有的数据) 该方法可以定义为静态的
static 关键字在实际项目的应用非常广泛
class Test{ int age; //普通成员 static String attribute = 奇女子 ; //静态成员 Test(){ } //静态块 static { System out println( 世间的奇女子们 ); } public static void FengJie(String n){ System out println(n + 是一个 + attribute); //System out println( QiNvZi s age is : + age); //无法从静态上下文中引用非静态变量age // method(); //无法从静态上下文中引用非静态方法 } public void method(){ System out println( 想要成为奇女子 ); } public void toBeQiNvZi(String n){ FengJie(n); System out println(n + 的年龄是: + this age); method(); } public static void main(String[] args){ System out println( ); System out println( 你是世间的 + Test attribute); System out println( 你是世间的 + attribute); System out println( ); FengJie( 凤姐 ); Test FengJie( 凤姐 ); System out println( ); Test t = new Test(); t age = ; t toBeQiNvZi( 芙蓉 ); t FengJie( 凤姐 ); } } lishixinzhi/Article/program/Java/hx/201311/25820 很赞哦! (1070)