JAVA中的static

1. static 变量

对于static来说是它其实是程序共享的变量 这个变量不属于任何对象,是一个公共变量,在使用时我们可以直接调用

也就是说当们调用某一类里的变量时我们需要先new这个对象然后用对象名.变量名来调用

而static的变量则不需要这样

举个简单的例子我们就可以明白了

  1. public class testStatic {
  2.     public static void main(String[] args) {
  3.         
  4.         /*test1 t1 = new test1();
  5.         System.out.println(t1.name);*/  //如果不是static变量那么我们就需要像这样new一个对象然后调用
  6.         
  7.         System.out.println(test1.name); //在这里我们不需要new对象而是直接使用类名.变量名调用
  8.         
  9.         test1 t1 = new test1();         //当我们new一个对象后可以调用该类的方法
  10.             t1.callname();
  11.             System.out.println(t1.name);// 也可以使用 对象名.变量名调用
  12.     }
  13. }
  14. class  test1{
  15.      public static String name="yuewei";    
  16.      
  17.      void callname(){
  18.          System.out.println(name);
  19.      }
  20. }
  21. /*打印出语句是 yuewei
  22.               yuewei
  23.               yuewei
  24. */

不知道这个例子大家明白否??

  1. //用static 我们可以做一些累加值的例子
  2. public class testcount {
  3.     
  4.     public static void main(String[] args) {
  5.         new testCount1("yuewei1");
  6.         new testCount1("yuewei2");
  7.         new testCount1("yuewei3");
  8.         new testCount1("yuewei4");
  9.         new testCount1("yuewei5");
  10.         
  11.         
  12. }
  13. }
  14. class testCount1{
  15.  public static int count =1;
  16. public  testCount1(String name){
  17.      System.out.println("My name is "+name+","+"I 'M NO:"+count);
  18.      count++;
  19.      
  20.  }
  21. }
  22. //在这里我们用到了累加,假如把static去掉看看结果是什么??
  23. //如果不使用static,他每调用一次构造函数,值都会变为原始值

 

2.static方法

我们在明白static变量后就很容易理解static方法了,就是在方法名前加static

举个简单的例子

  1. public class testmethod {
  2.     
  3.     public static void main(String[] args) {
  4.             test2.callname();   
  5.     }
  6. }
  7. class test2{
  8.     
  9.     public static String name="yuewei";
  10.     
  11.     public static void callname(){
  12.         System.out.println("My name is yuewei");
  13.     }
  14.     
  15. }

我们可以看到没有new test2()而是直接用类名.方法名。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值