1. static 变量
对于static来说是它其实是程序共享的变量 这个变量不属于任何对象,是一个公共变量,在使用时我们可以直接调用
也就是说当们调用某一类里的变量时我们需要先new这个对象然后用对象名.变量名来调用
而static的变量则不需要这样
举个简单的例子我们就可以明白了
- public class testStatic {
- public static void main(String[] args) {
- /*test1 t1 = new test1();
- System.out.println(t1.name);*/ //如果不是static变量那么我们就需要像这样new一个对象然后调用
- System.out.println(test1.name); //在这里我们不需要new对象而是直接使用类名.变量名调用
- test1 t1 = new test1(); //当我们new一个对象后可以调用该类的方法
- t1.callname();
- System.out.println(t1.name);// 也可以使用 对象名.变量名调用
- }
- }
- class test1{
- public static String name="yuewei";
- void callname(){
- System.out.println(name);
- }
- }
- /*打印出语句是 yuewei
- yuewei
- yuewei
- */
不知道这个例子大家明白否??
- //用static 我们可以做一些累加值的例子
- public class testcount {
- public static void main(String[] args) {
- new testCount1("yuewei1");
- new testCount1("yuewei2");
- new testCount1("yuewei3");
- new testCount1("yuewei4");
- new testCount1("yuewei5");
- }
- }
- class testCount1{
- public static int count =1;
- public testCount1(String name){
- System.out.println("My name is "+name+","+"I 'M NO:"+count);
- count++;
- }
- }
- //在这里我们用到了累加,假如把static去掉看看结果是什么??
- //如果不使用static,他每调用一次构造函数,值都会变为原始值
2.static方法
我们在明白static变量后就很容易理解static方法了,就是在方法名前加static
举个简单的例子
- public class testmethod {
- public static void main(String[] args) {
- test2.callname();
- }
- }
- class test2{
- public static String name="yuewei";
- public static void callname(){
- System.out.println("My name is yuewei");
- }
- }
我们可以看到没有new test2()而是直接用类名.方法名。