static
将static汇总一下吧,以后遇见也写在这,以防到处都有太混乱。
static关键字
通常来说,当创建类时,就是在描述那个类的对象的外观与行为。除非用new来创建那个类的对象,否则,实际上并未获得任何对象。执行new来创建对象时,数据空间才被分配,其方法才供外界调用。
但是,当声明一个事物是static时,就意味着这个域或方法不会与包含它的那个类的任何对象实例关联在一起。所以,即使从未创建某个类的任何对象,也可以调用其static方法或访问其static域。而非static域域和方法则必须知道它们一起运作的特定对象。
作用于字段:static int i=66;
作用于方法:
class MyClass{
static void test(){
...
}
}
当static作用于某个字段时:一个static字段对每个类来说都只有一份存储空间,而非static字段则是每个对象有一个存储空间。
当static作用于某个方法:static方法的一个重要用法就是在不创建任何对象的前提下就可以调用它。所以,这一点定义对main()方法很重要,因为main()方法是应用的入口,在没有任何对象的情况下就得到了执行。
无论创建多少个对象,静态数据都只占用一份存储区域。static关键字不能应用于局部变量,因此它只能作用于域。
再谈static
static方法可以不创建对象就可调用,即,static方法不需要对象的引用,所以也就没有this关键字。在static方法内部不能直接调用非静态方法(通常来讲,在同一个类中的方法,可以直接调用,不需this也不需创建对象,但static不同,不能直接调用,需要先创建对象,然后通过对象的引用来调用),反过来可以。
代码示例:
package Unity5;
public class flower {
String s="hello";
public void test(String s) {
System.out.println(this.s);
this.s=s;
System.out.println(this.s);
}
public static void main(String[] args) {
//flower f=new flower();
//f.test("world");
test("world");//编译器报错,因为不能在static方法中调用非static方法,提示在test方法前加static
}
}
按编译器提示,加上static之后:
package Unity5;
public class flower {
String s="hello";
public static void test(String s) {
System.out.println(this.s);//报错Cannot use this in a static context
this.s=s;//报错Cannot use this in a static context
System.out.println(this.s);//报错Cannot use this in a static context
}
public static void main(String[] args) {
//flower f=new flower();
//f.test("world");
test("world");
}
}
Comments | 0 条评论