java: static 关键字

static 关键字

在这里插入图片描述

public class Chinese {
	
	static String country;
	int age;
	String name;
	
	
	public static void test(){
		System.out.println("这是静态方法");
	}

	public static void main(String[] args) {
		Chinese.test();
		Chinese.country="中国";
		System.out.println(Chinese.country);
		
	}
}
这是静态方法
中国

在设计类的时候,分析哪些类属性不会因对象的不同而改变,将这些属性设置为类属性。相应的方法设置为类方法
类方法,也就是静态方法,比如工具类

工具类举例

public class utils {

	//判断方法是不是一个空字符串
	public static boolean isEmpty(String s){
		//在未来的 开发中,可能会多次使用这个判断,那么在大量的基础上看,就发现代码的重复很多了
		//所有把这一类方法给抽取到工具类做成一个方法
	    boolean flag=false;
		if(s !=null && !s.equals("")){
			flag=true;
			
		}
		
			return flag;
		
	}
	
	
	public static void main(String[] args) {
	
		String s="abx";
		String a="";
		String b=null;
		System.out.println(utils.isEmpty(s));//true
		System.out.println(utils.isEmpty(a));//false
		System.out.println(utils.isEmpty(b));//false
	}

}

类变量(类属性)被所有实例共享在这里插入图片描述

因为不需要实例就可以访问static方法,因此static方法内部不能有this,也不能有super

发布了45 篇原创文章 · 获赞 12 · 访问量 1121

猜你喜欢

转载自blog.csdn.net/weixin_46037153/article/details/104449865