Java static关键字

static关键字

static修饰属性和方法

1.static变量-类属性(静态属性)    

   static一般用public修饰

   static属性称为类属性,类属性保存在全局数据区中(方法区-所有对象共享区域),通过类名调用,与对象实例化无关。

传统属性具备的特征:保存在堆内存中,且每个对象独享属性。

描述共享属性,只需在属性前添加static关键字即可,访问static属性(类属性)应使用类名称.属性名

class Person{
    private String name;
    private int age;
    public static String country;      //共享属性
    public void setName(String name){
        this.name = name;
    }
    public String getName(){
        return name;
    }
    public void setAge(int age){
        this.age = age;
    }
    public int getAge(){
        return age;
    }
}
public class test{
     public static void main(String[] args){
         Person per1 = new Person();
         Person per2 = new Person();
         per1.setName("gx");
         per1.setAge(18);
         Person.country = "中国";    //通过类名调用
         per2.setName("sh");
         per2.setAge(90);
         System.out.println(per1.country);
         System.out.println(per2.country);
     }
 }

2.static方法-类方法(静态方法)

通过类名调用,与对象实例化无关。常见于工具类方法(例如:数组中的三种工具方法)

class Person{
    public static void fun(){
        System.out.println("我爱北京天安门");
    }
}
public class test{
     public static void main(String[] args){
         Person.fun();  //通过类名调用方法
     }
}

局部变量不能用static修饰

public class test{
     public static void main(String[] args){
        int static a = 1;   //局部变量
        System.out.println(a);
     }
}

关于static要注意的两点:

1.所有的static方法不允许调用非static定义的属性或方法

2.所有的非static方法允许访问static方法或属性

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

gx1500291

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值