Chinese
package day08;
public class Chinese {
// String country;
String name;//实例变量,只有实例化之后才能使用
String age;//实例变量,只有实例化之后才能使用
static String country;//类变量,不用实例化就能使用
}
TestChinese
package day08;
public class TestChinese {
public static void main(String[] args) {
// Chinese c1=new Chinese();
// c1.country="中国";
//
// Chinese c2=new Chinese();
// c2.country="中国";
//
// Chinese c3=new Chinese();
// c3.country="中国";
//
// 我们发现,上述每一个都要写“中国”,这样太麻烦,进而我们采用关键字static修饰变量,并在
// 测试类里写Chinese.country=“中国”
Chinese.country="中国";
Chinese c1=new Chinese();
Chinese c2=new Chinese();
Chinese c3=new Chinese();
System.out.println(c1.country);
//我们访问时,也不用上面的方法了,通常使用下面的方法
System.out.println(Chinese.country);
}
}
那么同样的,通过以上的分析,我们也可以用static修饰方法(比如说,main方法就是用static修饰过的)。
Chinese
package day08;
public class Chinese {
// String country;
String name;//实例比变量,只有实例化之后才能使用
String age;//实例比变量,只有实例化之后才能使用
static String country;//类变量,不用实例化就能使用
public static void pp(){
System.out.println("这个方法是static方法");
}
}
TestChinese
package day08;
public class TestChinese {
public static void main(String[] args) {
// Chinese c1=new Chinese();
// c1.country="中国";
//
// Chinese c2=new Chinese();
// c2.country="中国";
//
// Chinese c3=new Chinese();
// c3.country="中国";
//
// 我们发现,上述每一个都要写“中国”,这样太麻烦,进而我们采用关键字static修饰变量,并在
// 测试类里写Chinese.country=“中国”
Chinese.country="中国";
Chinese c1=new Chinese();
Chinese c2=new Chinese();
Chinese c3=new Chinese();
System.out.println(c1.country);
//我们访问时,也不用上面的方法了,通常使用下面的方法
System.out.println(Chinese.country);
Chinese.pp();
}
}
运行截图
例如我们平常会使用到的工具类
Utils
package day08;
//在未来的开发中,可能会多次使用一个方法,在大量的基础上,会发现代码的重复太多
//所以会创建一个“工具”类
public class Utils {
//判断字符串是不是一个空字符串,true返回不空
public static boolean isEmpty(String s){
boolean flag=false;
if (s!=null && !s.equals("")){
flag=true;
}
return flag;
}
}
TestUtils
package day08;
public class TestUtils {
public static void main(String[] args) {
String s="";
System.out.println(s.isEmpty());
}
}
运行截图