静态static
静态代码块一般作为读取项目的配置文件,整个系统中只读一次,执行顺序按照从上至下(都是static修饰的代码块)格式是:
public class A{
static {//静态代码块
}
{}//代码块
}
成员变量 没有static修饰的是实例变量,有static修饰是类变量
类变量:类变量是属于类的,是共享的数据,在内存中只有一份。
public static String nation="中国";//nation就是类变量,在整个项目运行过程中内存就此一份
public static void test();//这是静态方法
注意://在静态上下文中不能使用this和super关键字,不能调用非静态的方法,也不能访问实例变量,也不能被子类重写
//this.test2();—这是错误的,在静态方法里不能使用this和super
### 访问方法
- 类变量用类来访问 // Chinese.nation–建议这样访问
- 可以使用实例访问静态变量,但不建议 //Chinese c = new Chinese(); c.nation;
- 类方法(类静态方法)应该有类来调用// StaticDemo.test(); 用实例(对象)访问也可以,但不建议
/**要想在静态方法使用实例变量跟实例方法可以采用如下方法:
在静态方法中创建实例变量和实例方法所在的对象,通过这个对象来使用实例变量跟实例方法。如下*/
public class StaticTest {
int b = 14;
public void MyMethod(){
System.out.println("这是StaticTest的一个实例方法");
}
public static void MyStatic(){
StaticTest st = new StaticTest();
int e = st.b;
st.MyMethod();
}
}
代码的执行顺序
- 主调类的静态代码块
- 对象父类的静态代码块
- 对象的静态代码块
- 对象父类的非静态代码块
- 对象父类的构造函数
- 对象的非静态代码块
- 对象的构造函数
具体静态方法,静态变量(类变量)运用代码如下:
package com.gec.oop;
import java.util.Arrays;
class Person{
public static void test() {}
}
class Chinese extends Person{
//private String nation;//国籍
public static String nation = "中国";
private String name;
private String sex;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
//@Override
//public static void test() {}
}
public class StaticDemo {
int age = 3;
//静态方法 类方法
public static void test() {
System.out.println("static void test()");
//在静态上下文中不能使用this关键字,不能调用非静态的方法
//this.test2();
//不能访问实例变量
//System.out.println("age:" + age);
}
public void test2() {
System.out.println("test2()....");
}
public static void main(String[] args) {
Chinese c = new Chinese();
//c.setNation("中国");
c.nation = "cn";
System.out.println("c:" + c);
Chinese c2 = new Chinese();
//c2.setNation("中国");
c2.nation = "china";
System.out.println("c2:" + c2);
//类变量用类来访问
System.out.println(Chinese.nation);//china
System.out.println(c.nation);//可以使用实例访问静态变量,但不建议 china
System.out.println(c2.nation);//可以使用实例访问静态变量,但不建议 china
//类方法应由类调用
StaticDemo.test();
new StaticDemo().test();//不建议用实例访问静态方法
Arrays.parallelSort(new int[] {3,5,-2});
//不允许存在this
//System.out.println(this.age);
}
}