/*
* static 关键字
*1:加载时机:故静态变量随着类加载而加载(类一份,static也一份)就已经存在,而不是对象
*2:在一份内存空间中被共享 类变量 实例变量(方法)
* 类 yes no(还没出生对象)
* 对象 yes yes
* 3:关于静态方法:静态方法可以调用静态的属性和静态方法,不能调用属性和方法(对象的)
* 4:即在static声明中不能使用super和this
//5:被static修饰的方法只能重载,不能重写和覆盖
* 开发中,当前类是否被多个对象共用,或者常量设置为static类如Math.PI
* 工具类Arrays Math 故可以直接调 Math. Arrays.sort()
* */
public class StaticTest {
public static void main(String[] args)
{
//System.out.println(chinese.nation);
//格式 当前类.(静态属性)
//故静态变量随着类加载就已经存在,而不是对象
chinese c1 =new chinese();
c1.age=12;
c1.name="姚明";
chinese c2 =new chinese();
System.out.println(c1);
c2.age=15;
c2.name="易建联";
System.out.println(c2.toString());//c2.toString()
c1.nation ="CHI";
System.out.println(c1.nation);//CHI
System.out.println(c2.nation);//CHI仅此一份
c2.nation = "DP";
System.out.println(c1.nation);
System.out.println(c2.nation);
//均为DP
c1.show();
// 在主函数中如果采用调用非静态方法,必须先new 一个主函数类的对象
// methon3();//报错
StaticTest test1 = new StaticTest();
test1.methon3();//应该这样调用
//而采用非静态方法可以直接
methon4();//静态,相当于省略为 StaticTest.methon4();
StaticTest.methon4();
}
//以下是main中书写的两个方法
public void methon3(){
System.out.println("我是静态测试1");
}
public static void methon4(){
System.out.println("我是静态测试2");
}
}
class chinese{
String name;
int age;
static String nation="中国";//静态变量,类变量,仅此一份
@Override
public String toString() {
return "Chinese{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
public void eat(String name){
System.out.println("爱吃:" + name);
}
public void show(){
methon1();//可以调用静态结构
//eat();//非静态方法不能调用非静态方法,以为还没有new对象
}
public static void methon1(){
String name1;
System.out.println("我是静态方法的测试");
}
public static void methon2(){
System.out.println("我是类的非静态方法");
//可以调用静态的属性即方法
methon1();
}
}