STATIC关键字有哪些作用

    下面通过四个方面对static关键字的作用做以简单的说明,话不多说,直接上代码:
package com.hzyc.Class;

//import java.util.List;


//采用static修饰的静态变量,可以采用以下两种方式进行调用:
		/*
		 * 1、类.静态变量
		 * 2、对象.静态变量
		 * 
		 * 采用static修饰的静态变量,可类似的代替全局变量,类似于类,在内存中只存在一个复制,
		 * 所有的实例都指向同一个内存
		 * */
/*
 * 实例变量:不用static修饰的变量,因而变量的调用方式只有一种:
 * 			1、对象.实例变量
 * 它在内存中存在多个复制
 * 
 * 
 * */
public class Assert {
	public static int staticInt=0;
	public int nonStaticInt=0;
	public static void main(String[] args) {
		Assert t= new Assert();
		System.out.println("t.staticInt="+t.staticInt);
		System.out.println("Assert.stsicInt="+Assert.staticInt);
		System.out.println("t.nonStaticInt="+t.nonStaticInt);
		System.out.println("对静态变量和实例变量分别+1");
		t.nonStaticInt++;
		Assert.staticInt++;
		t.staticInt++;
		Assert t1= new Assert();
		System.out.println("t1.staticInt="+t1.staticInt);
		System.out.println("Assert.stsicInt="+Assert.staticInt);
		System.out.println("t1.nonStaticInt="+t1.nonStaticInt);
		
	}
}
	/*
	 * Java同时提供了static方法和非static方法:
	 * 		1、static方法时类的方法,不需要创建对象即可被调用。
	 * 		2、非static方法是对象的方法,只有对象被创建出来时之后才可以被使用。
	 * static方法中不能使用super关键字,不能调用非static方法,只能访问所属类的静态成员变量和方法。也不能访问非static
	 * 类型的变量。
	 * *****static一个很重要的用途是为了实现单例模式。单例模式就是该类智能有一个实例,为了实现这一功能,
	 * *****必须隐藏类的构造函数,即把构造函数声明为private,并提供一个创建对象的方法,。
	 * */
class Singleton{
	private static Singleton instance=null;
	private Singleton(){};
	public static Singleton getInstance() {
		if(instance==null) {
			instance=new Singleton();
		}
		return instance;
	}
}
/*
 * static代码块:
 * 		静态代码块是类中独立于成员变量和成员函数的代码块。它不在任何一个方法体内,JVM在加载类是会执行代码块,如果有
 * 多个代码块,JVM将按照顺序来执行。
 * ¥¥静态代码块常用来初始化静态变量,同时,静态代码块只会被执行一次。
 * 
 * */
class Test1{
	private static int a;
	static {
		Test1.a=4;
		System.out.println(a);
		System.out.println("static block is called");
	}
	public static void main(String[] args) {
		
	}
}
/*
 * static内部类:
 * 		static内部类是指被声明为static的内部类,它可以不依靠于外部类实例对象而被实例化,而通常的内部类需要等外部类
 * 实例化后才能被实例化。
 *      static内部类只能访问外部类中的静态成员和静态方法(包括私有类型)
 * 
 * &&只有内部类才能被定义为static
 * */
class Outer{
	static int n=5;
	static class inner{
		void acessAttrFromOuter(){
			System.out.println("Inner:Outer.n="+n);
		}
	}
	public static void main(String[] args) {
		Outer.inner nest = new Outer.inner();
		nest.acessAttrFromOuter();
	}
}

/*
 * Java语言中:
 * 		1、对于变量,若使用static final 修饰,则表示一旦赋值,就不可修改
 * 		2、对于方法,若使用static final修饰,则表示该方法不可被覆盖,并且可以通过类名直接访问
 * 
 * */
























	


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值