下面用Test类为例讲解static的使用方法:
class Test{
public static int a =1;
public final static int b;
static {
b = 200;
System.out.println("这是静态代码块");
}
public static void print(){
//这是错误的,静态方法中不能有this和super等关键字
// this.a = 20;
System.out.println("这里测试static方法print和static变量a,a=="+a);
}
//这是错误的,static不能跟abstract合用
// static abstract testAbstract();
void testLocalVariable(){
//这是错误的,static不能修饰局部变量
// static int a=0;
}
//这是错误的,static不能修饰构造方法
// static Test(){
// //构造方法
// }
void testThis(){
this.a = 10;
System.out.println("这里测试this.a=="+this.a);
}
}
class ChildTest extends Test{
public static void childPrint(){
//这是错误的,静态方法中不能有this和super等关键字
// super.print();
}
//static对字类继承、覆盖和重载父类方法没有影响
public static void print(){
}
}
第一,static修饰的方法或变量,都是属于类的,是全局的方法和变量,在类的实例之间共享。调用形式是"类名.方法(参数)"和"类名.变量名".例如:
public class StaticTest {
public static void main(String[] args) {
//通过“类名.变量名”访问全局的类变量
System.out.println("这里测试static变量=="+Test.a);
//通过"类名.方法名(参数)"访问全局的方法
Test.print();
Test test = new Test();
//也可以,通过“对象.变量名”访问全局的类变量
test.a = 10;
//也可以,通过"对象.方法名(参数)"访问全局的方法
test.print();
}
}
第二,static不能与abstract连用
第三,static不能修饰局部变量
第四,static不能修饰构造方法
第五,static和final合用,表示静态常量,不能改变其值。可以在声明时赋值,也可以在静态代码块中赋值。之后该变量的值不能在改变。
第六,static修饰代码块,使其成为静态代码块。静态代码块之在JVM加载类的时运行一次,之后再也不会运行。
第七,static修饰内部类,使其成为静态内部类。静态内部类与内部类的不同在于创建实例的形式不同。
public class StaticTest {
public static void main(String[] args) {
//创建静态内部类实例
//使用“包名.外部类名.内部类名 实例名 = new 包名.外部类名.内部类名(构造方法参数)”的形式创建
Test.Person person = new Test.Person();
person.name = "张三";
person.print();
//创建内部类实例
Test test = new Test();
//使用“包名.外部类名.内部类名 实例名 = 外部类实例名.new 内部类名(构造方法参数)”的形式创建
Test.People people = test.new People();
}
}
class Test{
//静态内部类
static class Person {
public String name;
public void setName(String name){
this.name = name;
}
void print(){
System.out.println("name=="+name);
}
}
//内部类
class People{
}
}

被折叠的 条评论
为什么被折叠?



