static关键字:

2018-05-15  本文已影响0人  公子请留步LookMe

1、可以通过类直接去访问,(不需要实例化出对象就可以调用函数或者变量)

2、在一个类当中成员变量用static修饰过后。该类的所有对象共用这个属性的内存地址。

3、static修饰的方法,只能调用static修饰的方法。如果想要调用非static修饰的方法,就必需通过类的对象去调用。

如:
public class Test {
    public static void main(String[] args) {
          Test t = new Test();
          t.fun1();  //通过对象去调用
         
        fun1();//不能直接调用
}

public void fun1() {
        fun2();
        fun3();
        Cat c2 = new Cat();
        c2.printCat2();
}


static关键字test:
public class Test5 {
 private static int a;
 private int b;
 static{
  Test5.a=3;
  System.out.println(a);
  Test5 t=new Test5();
  t.f();
  t.b=1000;
  System.out.println(t.b);
 } 
 static{
  Test5.a=4;
  System.out.println(a);
 }   
 public static void main(String[] args) {
  // TODO 自动生成方法存根
 } 
 static{
  Test5.a=5;
  System.out.println(a);
 } 
 public void f(){
  System.out.println("hhahhahah");
 }
}
运行结果:
3
hhahhahah
1000
4
5
上一篇 下一篇

猜你喜欢

热点阅读