java中静态变量,方法,类的使用实例
class StaticTest
{
static int i=1;
static
{//静态区域块,静态区域块只能执行一次
i++;
}
public StaticTest()
{
i++;
}
public static void main(String[] args)
{
Static s1=new Static();
System.out.println(s1.i);
Static s2=new Static();
System.out.println(s2.i);
Student stu1=new Student(15,"张三",250);
Student stu2=new Student(16,"李四",260);
System.out.println(Student.getTotalFee());
}
}
/**
*增加学生类
*/
class Student
{
int age;
String name;
int fee;
static int totalFee;
public Student(int age,String name,int fee)
{
this.age=age;
this.name=name;
this.fee=fee;
totalFee+=fee;
}
//这是一个静态方法,即类方法,所有的对象都共享一个方法,节省栈的开销
public static int getTotalFee()
{
return totalFee;
}
}