您的位置:首页 > 编程语言 > Java开发

JAVA学习日志(6-1-静态修饰符与主函数)

2016-07-13 00:00 423 查看
关键字static(静态):

是一个修饰符,用于修饰成员(成员变量,成员函数)

修饰之后不再存在于堆内存中,每一个对象都可以访问,并被对象共享(见上一篇博文)

当成员被static后,除了可以被对象调用外,还可以直接被类名调用(类名.静态成员)

class catShit{
private static int weight;
private String color;
{
System.out.println("Meowuuuuuuu");
}
catShit(int weight){
this.weight=weight;
}
catShit(String color){
this.color=color;
}
catShit(int weight,String color){
this.weight=weight;
this.color=color;
}
public static void seeShit(catShit x){
if(x.weight>100){
System.out.println("HOLY CATSHIT!");
}
else{
System.out.println("Eyooooooooo!");
}
}
public boolean compare(catShit c){
return this.weight==c.weight;
}
}
class shitDemo{
public static void main(String[] args){
catShit i=new catShit(101);
catShit.seeShit(i);
catShit j=new catShit(99);
catShit.seeShit(j);
boolean b=i.compare(j);
System.out.println(b);
}
}

最后输出结果为true

被static修饰的成员属于方法区(也称共享区,数据区)

特点:随着类的加载而加载;

优先于对象存在;

被所有对象共享;

可以直接被类名所调用;

eg. String name--------成员变量,实例变量

static String name-------静态成员变量,类变量

实例变量与类变量区别:

存放位置:类变量随着类的加载而存在于方法区;

实例变量随着对象的建立而存在于堆内存中;

生命周期:类变量生命周期最长,随着类的消失而消失;

实例变量生命周期随着对象的消失而消失;

使用注意事项:

静态方法只能访问静态成员(方法、变量)

非静态方法既可以访问静态,也可以访问非静态

静态方法中不可以定义this,super关键字

主函数是静态函数

静态的优点:对对象的共享数据进行单独空间的存储,节省空间

可以直接被类名调用

缺点:生命周期过长

访问出现局限性(只能访问静态)

main函数(主函数)

是一个特殊函数,可以被jvm调用,作为程序入口。

定义:public——代表该函数访问权限是最大的

static——代表主函数随着类的加载就已经存在

void——代表主函数没有具体的返回值

main——不是关键字,但是是一个特殊单词,可以被jvm识别

(String[] args)——函数的参数,参数类型是一个数组,元素是字符串

主函数是固定格式的,jvm识别。只有args(arguments)可以任意更改

jvm在调用主函数是,传入的是new String[0];

class MainDemo{
public static void main(String[] args){
String[] arr={"haha","hehe","heihei","hiahia"};
MainTest.main(arr);
}
}
class MainTest{
public static void main(String[] args){
for(int x=0;x<args.length;x++){
System.out.println(args[x]);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: