你不可不知的static(3)-注意事项、区别成员变量、静态main

来源:互联网 发布:自定义打印软件 编辑:程序博客网 时间:2024/05/24 05:43

今天我们一起学习一下static的注意事项、和成员变量的区别以及静态main方法。

(1)注意事项;
A:在静态方法中没有this对象
B:静态只能访问静态,非静态可以访问静态(代码测试)

我们在Person类中添加如下代码:

int thisNum = 100;static int thisNumStatic = 200;public void show(){System.out.println(this.thisNum);System.out.println(thisNumStatic);staticShow();}public static void staticShow(){//System.out.println(this.thisNum);//Cannot use this in a static context//show();//Cannot make a static reference to the non-static method show() from the type PersonSystem.out.println(thisNumStatic);}


如注释,故需谨记:static随着类的加载而加载,this随着对象的创建而创建,静态比对象先存在。


(2)和成员变量的区别
A:所属不同
静态变量:属于类,类变量
成员变量:属于对象,对象变量,实例变量
B:内存位置不同
静态变量:方法区的静态区
成员变量:堆内存
C:生命周期不同
静态变量:静态变量是随着类的加载而加载,随着类的消失而消失
成员变量:成员变量是随着对象的创建而存在,随着对象的消失而消失
D:调用不同
静态变量:可以通过对象名调用,也可以通过类名调用
成员变量:只能通过对象名调用
(3)静态的main方法:

public:权限最大
static:不用创建对象调用

void:返回值给jvm没有意义
main:就是一个常见的名称。
String[] args:可以接收数据,提供程序的灵活性
我们写一下代码:

System.out.println("args:" + args);System.out.println("args.length:" + args.length);for(String temp : args){System.out.print(temp + " ");}

我们先编译:

javac StaticTest.java

然后运行:

java StaticTest Hello World Java

输出结果:



0 0