实验6 static变量和static方法
一、实验目的
1. 理解static变量和实例变量的不同。
2. 理解static方法和实例方法的不同。
3. 了解jvm的内存管理,并能够掌握局部变量和成员变量的生存期。
二、实验内容
1.对下面程序进行分析,给出实验结果,并对实验结果进行解释。public class StaticExample {
static int globalCount;
public static void main(String[] args) {
StaticExample example1 = new StaticExample();
StaticExample example2 = new StaticExample();
example1.globalCount++;
example2.globalCount++;
System.out.println("" + example1.globalCount);
System.out.println("globalCount of example2 = " + example2.globalCount);
System.out.println("globalCount = " + StaticExample.globalCount);
}
}
结果:
globalCount of example1 = 2;
globalCount of example2 = 2;
解释:静态变量被实例所共享。
//
2.定义一个班级成员类,Soft2Member。
要求如下:属性:姓名,性别,年龄。
静态属性:人数。
方法:自我介绍(输出个人信息)。
构造方法:每增加一个成员,人数+1.
静态方法:输出当前班级人数。
3. 定义一个测试类:TestMember
要求如下:在主程序中,生成多个Soft2Member对象,最终输出班级人数,并让每个对象做自我介绍。
package itcost.cn;
class TestNumber{
public static void main(String[]args) {
Soft2Member s1=new Soft2Member("王珂","女",21);
Soft2Member s2=new Soft2Member("李华","男",23);
Soft2Member s3=new Soft2Member("刘志","男",20);
Soft2Member s4=new Soft2Member("张丽","女",19);
System.out.println("班级总人数:"+Soft2Member.getNumber());
}
}
class Soft2Member{
String name, sex;
int age;
static int num;
Soft2Member(String name,String sex,int age){
this.name=name;
this.sex=sex;
this.age=age;
System.out.println("姓名:"+name);
System.out.println("性别:"+sex);
System.out.println("年龄:"+age);
num++;
}
public static int getNumber(){
return num;
}
}