静态修饰static

静态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();
    }

}

代码的执行顺序

  1. 主调类的静态代码块
  2. 对象父类的静态代码块
  3. 对象的静态代码块
  4. 对象父类的非静态代码块
  5. 对象父类的构造函数
  6. 对象的非静态代码块
  7. 对象的构造函数

具体静态方法,静态变量(类变量)运用代码如下:

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);
		
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值