static 修饰符

2018-03-09  本文已影响0人  乐云纤地

static 修饰符

静态变量:

static 关键字用来声明独立于对象的静态变量,无论一个类实例化多少对象,它的静态变量只有一份拷贝。 静态变量也被称为类变量。局部变量不能被声明为 static 变量。

静态方法:

static 关键字用来声明独立于对象的静态方法。静态方法不能使用类的非静态变量。静态方法从参数列表得到数据,然后计算这些数据。

静态方法里面只能访问静态变量。

public static 表示公共的静态方法;

public 表示公共的方法;

静态方法不需要实例化,直接通过 类名.方法()调用;

公共方法需要实例化,通过new 类名.方法()调用;

静态变量与静态方法类似。所有此类实例共享此静态变量,也就是说在类装载时,只分配一块存储空间,所有此类的对象都可以操控此块存储空间,当然对于final则另当别论了。

例子:

package com.utils;

public class StaticTest {

//静态变量staticInt

private static  int staticInt =5;

private int random =2;

private Stringformat;

private static Stringa="a";

static String b="";

public  String getFormat() {

return this.format;

}

//公共静态方法getA() 只能访问静态变量

    public static String getA(){

return a;

}

//表示公共方法

    public void setFormat(String format) {

this.format = format;

}

public StaticTest() {

//静态变量staticInt 可以做算法累加OR类减等

      staticInt++;

random++;

System.out.println("staticInt = "+staticInt+"  random = "+random);

}

public static void main(String[] args) {

//公共方法需要实例化,通过new 类名.方法()调用

StaticTest test =new StaticTest();

StaticTest test2 =new StaticTest();

test.setFormat("a");

test.getFormat();

//静态方法不需要实例化,直接通过 类名.方法()调用;

      b= StaticTest.getA();

System.out.println("static Int = "+test.staticInt+" static Int 2= "+test2.staticInt);

System.out.println("b = "+b);

}

}

上一篇 下一篇

猜你喜欢

热点阅读