静态成员方法与静态成员变量【java版】
一、类的定义
package com.statickeyword;
public class staff {
private staticstringcountry="china";
private int id;
private string name;
static voidsetcountryandprint(string _country)
{
country=_country;// 由于country不是专属某个特定的类,因此不能以this.country=country;的形式访问
system.out.println("the new country is : "+country);
}
staff(int id,string name)
{
this.id=id;
this.name=name;
}
void printcountry()
{
system.out.println("my country is : "+country);
}
}
二、静态成员函数
a)只可访问静态成员变量
public static void main(string[] args) {
/*虽然也可以用staff_a.setcountryandprint("japan")的形式访问,但是为了
* 体现静态方法的运行与任何具体对象都无关,故提倡用“类名.静态方法”的形式访问
*/
staff.setcountryandprint("japan");
}
运行结果:
b)无法访问非静态成员变量
如果修改静态成员函数,使其访问非静态成员变量
static voidsetcountryandprint(string _country)
{
name="testname";//实际上并不能访问非静态成员变量
country=_country;// 由于country不是专属某个特定的类,因此不能以this.country=country;的形式访问
system.out.println("the new country is : "+country);
}
运行结果:
说明:1)由于在调用静态成员方法时,并不会将对象的引用传递过去,因此不能访问对象的非静态成员变量
静态成员方法访问方式:“类名.静态方法”
2)而且由于静态成员方法通常以“类名.静态方法”的形式访问,如果可以访问“非静态成员变量”,那么
编译器也就无法确定:访问的“非静态成员变量”是属于哪个对象,在内存中的位置,甚至根本就还没有对象,
为避免这种情况的出现,编译器一定不会允许“静态成员方法”访问“非静态成员变量”
三、静态成员变量
静态成员变量:位于“数据区”,无论多少个对象该变量在内存中都只有一份
非静态成员变量:位于“堆空间”,每new一个对象创建一份,因此有多少个对象该变量在内存就有多少份
a)静态成员方法访问
显然可以访问,同【二(a)】,略
b)非静态成员函数访问
public static void main(string[] args) {
// todo auto-generated method stub
staff staff_a=new staff(1,"evens");
staff_a.printcountry();
}
运行结果:
======================================================
在最后,我邀请大家参加新浪APP,就是新浪免费送大家的一个空间,支持PHP+MySql,免费二级域名,免费域名绑定 这个是我邀请的地址,您通过这个链接注册即为我的好友,并获赠云豆500个,价值5元哦!短网址是http://t.cn/SXOiLh我创建的小站每天访客已经达到2000+了,每天挂广告赚50+元哦,呵呵,饭钱不愁了,\(^o^)/