Java之static 关键字

Java 之static关键字

头脑风暴,大致列举了static的基本用法

1. static静态关键字,此关键字表示修饰的对象是静态的,所修饰的对象(变量或者方法)仅此一个,其生命周期不受抽象对象的实例化的影响。
2.静态方法中只能调用静态变量
3.调用方法:如果一个方法是静态方法,调用方式和非静态方法不一样。通常, 调用方法的方式有两种。
  其一: 先实例化对象,然后用对象来调用。

            Persion mPerson = new Person();
            mperson.function();
      其二: 直接用类名+“."+方法名(这是普通非静态方法没有的)
           Person.function();
4. static 之修饰变量,方法,代码块,感觉中心思想类似,区别有空来区分。
5. 特殊情况:如果static修饰的是内部静态类,那么它是可以被通过new来实例化的 ,此时存放在堆区.

package com.example.testtwo;

public class myClass {
    /*This is a inner class, just do something!*/
    public static class Person{
        public synchronized void callForHelp(){
            try {
                System.out.println("start----- curentThreadId ="+Thread.currentThread().getId());
                Thread.sleep(1000);
            } catch (InterruptedException E){
                E.printStackTrace();
            }
            System.out.println("end-----");
        }
    }
    /*A inner class which can be be instance by new*/
    public static class MyThread extends Thread{
        @Override
        public void run() {
            Person mPerson = new Person();
            mPerson.callForHelp();
        }
    }

    public static void main(String[] args){
        for (int i= 0; i<3; i++){
            MyThread myThread = new MyThread();
            myThread.start();
        }
    }
}

结果:
start----- curentThreadId =12
start----- curentThreadId =11
start----- curentThreadId =13
end-----
end-----
end-----
 

Process finished with exit code 0

从Demo 中可以看出,主函数中实例化的三个线程是不同的.

6.  static 修饰代码块
今天看项目代码无意间看到一段,涨见识了:

package com.example.testfive;


public class myClass {
    static {
        for (int i= 0; i<2; i++) {
            System.out.println("This is a test for static!");
        }
    }

    public static void main(String[] args){
        System.out.println("Test");
    }
}

输出:
This is a test for static!
This is a test for static!
Test

Process finished with exit code 0

从输出可以看出:其一,静态代码运行在主函数运行之前.其二,找到一种处理静态变量的方法.后一种方法应该会用到的.

有新发现会补充.谢谢.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值