JAVA修饰属性_java中static关键字修饰属性和方法

static关键字的作用: 1、使用static关键字修饰一个属性 声明为static的变量实质上就是全局变量

2、使用static关键字修饰一个方法 通常,在一个类中定义一个方法为static,那就是说,无需本类的对象即可调用此方法

3、使用static关键字修饰一个类型(内部类)

未使用static关键字前代码:

public class StaticTest{

public static void main(String[] args){

Role beibei = new Role("刘备","蜀国");

Role fefei = new Role("张飞","蜀国");

Role yunchang = new Role("云长","蜀国");

System.out.println(beibei.getInfo());

System.out.println(yunchang.getInfo());

System.out.println(fefei.getInfo());

}

}

//角色

class Role{

private String name;

private String country;

public Role(String name,String country){

this.name = name;

this.country = country;

}

public void setName(String name){

this.name = name;

}

public String getName(){

return name;

}

public void setCountry(String country){

this.country =country;

}

public String getCountry(){

return country;

}

public String getInfo(){

return "name="+name+"country="+country;

}

}

/**

运行结果:

name=刘备country=蜀国

name=云长country=蜀国

name=张飞country=蜀国

*/

三个对象会分别new出三个地址空间,存放三份相同的country=蜀国,若只想country定值蜀国,需引入静态修饰符static。

使用static关键字后代码:

public class StaticTest1{

public static void main(String[] args){

Role beibei = new Role("刘备");

Role fefei = new Role("张飞");

Role yunchang = new Role("云长");

System.out.println(beibei.getInfo());

System.out.println(yunchang.getInfo());

System.out.println(fefei.getInfo());

}

}

//角色

class Role{

private String name;

private static String country = "蜀国";//静态变量(全局变量)

public Role(String name){

this.name = name;

}

public void setName(String name){

this.name = name;

}

public String getName(){

return name;

}

public String getInfo(){

return "name="+name+"country="+country;

}

}

/**

运行结果:

name=刘备country=蜀国

name=云长country=蜀国

name=张飞country=蜀国

*/

静态方法区:存储静态变量,类信息(方法)

static关键字 1、静态变量或方法不属于对象,依赖类 2、静态变量是全局变量,生命周期从类被加载后一直到程序结束 3、静态变量只有存一份,在静态方法区中存储 4、静态变量是本类所有对象共享一份 5、建议不要使用对象名去调用静态数据,直接使用类名调用 6、stitic修饰一个方法,那么该方法属于类,不属于对象,直接使用类名调用 7、静态方法不能访问非静态属性和方法,只能访问静态

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值