静态变量(被static修饰的成员变量) | 静态方法(被static修饰的成员方法) |
---|---|
●特点: 被该类所有对象共享 | ●特点: 多用在测试类和工具类中,Javabean类中很少使用 |
●调用方式: 类名调用(推荐) 对象名调用 | ●(调用其他类中的静态方法时)调用方式: 类名调用(推荐) 对象名调用 ●(调用本类中的静态方法时)调用方式: 直接方法名调用就行了 |
内存: 静态变量是随着类的加载而加载的,优先与对象出现的 |
Javabean类 | 用来描述一类事物的类.比如Student,Teacher,Dog等 |
测试类 | 用来检查其他类是否书写正确,带有main方法的类,是程序的入口 |
工具类 | 不是用来描述一类事物的类,而是帮我们做一些事情 |
1.类名见名知意 |
2.私有化构造方法(这样就无法在测试类创建其对象了,因为工具类不描述事物,创建其对象毫无意义) |
3.方法定义为静态(这样可以类名调用工具类里的方法了,比较方便) |
静态方法中,只能访问静态 |
非静态方法可以访问所有 |
静态方法中没有this关键字 |
public class Student {
//静态变量
public static String teacherName;
//成员变量
private String name;
private int age;
//空参构造
public Student() {
}
//全参构造
public Student(String name, int age) {
this.name = name;
this.age = age;
}
//get和set
public static String getTeacherName() {
return teacherName;
}
public static void setTeacherName(String teacherName) {
Student.teacherName = teacherName;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
//成员方法1
public void study() {
System.out.println(name + "正在学习!");
}
//成员方法2
public void show() {
System.out.println(name + " " + age + " " + teacherName);
}
}
public class Test {
public static void main(String[] args) {
Student.teacherName = "石老师";//类名调用静态变量
Student s1 = new Student("彭于晏", 18);
s1.show();//打印结果: 彭于晏 18 石老师
s1.study();//打印结果: 彭于晏正在学习!
Student s2 = new Student("吴彦祖", 19);
s2.show();//打印结果: 吴彦祖 19 石老师
s2.study();//打印结果: 吴彦祖正在学习!
}
}
//工具类
public class ArrayUtil {
//静态方法1
public static String printArray(int[] arr) {
StringBuilder sb = new StringBuilder();
sb.append("[");
for (int i = 0; i < arr.length; i++) {
if (i == arr.length - 1) {
sb.append(arr[i]);
} else {
sb.append(arr[i]).append(", ");
}
}
sb.append("]");
return sb.toString();
}
//静态方法2
public static double getAverage(double[] arr) {
double sum = 0;
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum / arr.length;
}
}
public class Test {
public static void main(String[] args) {
int[] arr1 = {10, 20, 30, 40, 50};
String str = ArrayUtil.printArray(arr1);//类名调用工具类中的静态方法1
System.out.println(str);//打印结果: [10, 20, 30, 40, 50]
double[] arr2 = {2.3, 3.7, 4.2, 7.8};
double avg = ArrayUtil.getAverage(arr2);//类名调用工具类中的静态方法2
System.out.println(avg);//打印结果: 4.5
}
}