学习的过程就是填坑的过程。不要偷懒,想着跳过它。如果你现在跳过它,就等于给自己挖了一个坑。你迟早会陷入其中。为避免掉坑,尽量填坑。我们走吧!如果没有静电会怎样?需求:1.定义Student类的姓名和国籍,说话行为的多种结构,以及重载的形式2.确定学生的国籍,可以显示和初始化国籍publicclassStudent{Stringname;Stringcountry;//国籍publicStudent(Stringname,Stringcountry){this.name=name;this.country=country;}publicvoidspeak(){System.out.println("姓名:"+this.name+""+"国籍:"+this.country);}}classTest{publicstaticvoidmain(String[]args){Studentstudent=newStudent("何道昌","中国");Studentstudent1=newStudent("孙双双","中国");学生。speak();student1.speak();}}运行结果:姓名:何晶晶国籍:中文姓名:孙双双国籍:中国当前问题:现在我们知道所有学生都是中国人,现在我们创建一个学生对象,必须给所有学生的国籍属性赋相同的值,这样会造成堆内存空间资源的浪费。目前的解决方案:将数据“China”移动到数据共享区,将此数据共享给所有Student对象使用。将这些数据移动到数据共享区怎么样?解决方法:只需要用static修改数据即可。静态成员变量只会在数据共享区维护,非静态成员变量的数据会存放在每个对象中维护一份publicclassStudent{Stringname;//name//用static修饰country,然后country此时是共享数据staticStringcountry="China";//国籍//构造函数publicStudent(Stringname){this.name=name;}//说话行为publicvoidspeak(){System.out.println("姓名:"+this.name+""+"国籍:"+国家);}}classTest{publicstaticvoidmain(String[]args){Studentstudent=newStudent("何道长");Studentstudent1=newStudent("孙双双");student.speak();student1.speak();}}运行结果:姓名:何晶晶国籍:中文姓名:孙双双国籍:中国下面详细解释一下static静态(静态修饰符)1.static修饰静态变量如果有数据需要共享给所有对象,那么可以使用static修饰静态成员变量访问方法:方法一:可以使用对象访问格式:对象。变量名方法二:可以用类名访问格式:类名。变量名注:1)。非静态成员变量只能使用对象Access访问,不能使用类名访问publicclassStudent{Stringname;//命名非静态成员变量//使用static修饰country,那么此时country是共享数据staticStringcountry="China";//国籍静态成员变量//构造函数publicStudent(Stringname){this.name=name;}//说话行为publicvoidspeak(){System.out.println("Name:"+this.name+""+"Nationality:"+country);}}classTest{publicstaticvoidmain(String[]args){Studentstudent=newStudent("何道场");System.out.println(student.name);//使用对象访问非-静态变量
