首先说一下static关键字,
<1>static--修饰成员变量
1.--用static修饰的成员变量不属于对象的数据结构;
2.--static变量是属于类的变量,通常可以通过类名来引用static成员;
3.--static成员变量和类的信息一起存储在方法区,而不是在堆中;
4.--一个类的static成员变量只有“一份”,无论该类创建了多少对象。
通过下图来理解一下static修饰成员变量的意义。。。
<2>static关键字--修饰方法
1.——通常的方法都会涉及到对具体对象的操作,这些方法在调用时,需要隐式的传递对象的引用,
int d = p1.distance(p2);//这个p1等同于这个this
/*
调用distance方法时,除了传递p2参数外,还隐式的传递了p1作为参数没在方法中的this关键字即表示该参数
*/
2.——static修饰的方法不需要针对某些对象进行操作,其运行结果仅仅与输入的参数有关,调用时直接类名引用。
/*
该方法在调用时,没有隐式的传递对象使用,因此在static方法中不可以使用this关键字
*/
double c = Math.sqrt(3.0*3.0+4.0*4.0);
<2>static关键字--修饰方法的意义
1.——由于static在调用时没有具体的对象,因此在static方法中不能非static成(对象成员)进行访问。static方法的作用在于提供一些“
工具方法”和“
工厂方法”等、
2.
静态方法是属于类的方法
下面是我自己的一个个人笔记
实例化:创建对象的过程
实例:实际的例子-----------对象
class Aoo{
int a;-------------属于对象
static int b;------属于类
void show(){
b++;
}
}
成员变量:
1)实例变量-----不用static修饰的
2)静态变量-----static修饰的
何时用静态变量,何时用实例变量
class Customer{ //帐户类
String customerName; //帐户名称
String customerPwd; //帐户密码
static double poir; //利率
}
实例变量:属于对象,一个对象有一份
静态变量:属于类,所有对象公用这一份
Customer zs = new Customer();
zs.customerPwd = 123456;
Customer ls = new Customer();
ls.customerPwd = 654321;
类的方法中,常常需要对对象的实例变量操作
类的非静态方法,默认有个隐式的this
类的静态方法,没有隐式的this的
class Cell{
int row; //属于对象---实例变量
int col; //属于对象---实例变量
static int num;
static void show(){
row++; //错误的
num++; //正确的
Cell c = new Cell();
c.row = 5;
}
void drop(){
this.row++;
}
void moveLeft(){
this.col--;
}
}
main(){
Cell c1 = new Cell(2,5);
c1.drop(); //3,5
Cell c2 = new Cell(6,7);
c2.drop(); //7,7
}
非静态方法:---有隐式this
可以直接访问静态变量和实例变量
需要访问实例变量时用
静态方法:-----没有隐式this
只能直接访问静态变量,不能直接访问实例变量
不需要访问实例变量时,只需对参数操作即可
何时用静态方法,何时用非静态方法:
静态方法,只与参数相关,与实例变量有关
Arrays.sort(arr);
Math.random();
Math.sqrt(25);
何时用静态代码块:
一般用于加载静态资源(图片、音频、视频)
这个是我自己一个完整代码
//static的演示
public class StaticDemo {
public static void main(String[] args) {
Loo o1 = new Loo();
o1.show();
Loo o2 = new Loo();
o2.show();
System.out.println(Loo.b);//建议类名来访问
System.out.println(o1.b);//不建议通过引用来访问
System.out.println("--------------------");
Loo o3 = new Loo();
o3.show();
Loo o4 = new Loo();
o4.show();
}
}
class Moo{
int a;
static int b;
void show(){
a = 1;
b = 2;
}
//没有隐式的this
static void test(){//静态的什么时候都能访问
//a = 1; 没有this就没有对象。而a必须通过对象来访问
b = 2;
}
}
class Loo{
int a;
static int b;//静态变量
Loo(){
a++;
b++;
}
void show(){//实例方法----隐式this
System.out.println("a="+a);
System.out.println("b="+b);
}