Java 面向对象-静态字段和方法
2020.02.27 20:24
2020.02.27 20:24
1. 静态字段
在之前我们写的所有代码中,类中的所有字段都是实例字段,该字段的特点是:为具体实例所拥有,互不影响;
而除了这种实例字段还有一种静态字段,用static
修饰,该字段特点是:所有实例都会共享该字段,你可以理解该字段属于这个类,而不属于某个实例。
请看实例代码:
Student.java
package test06;
public class Student {
public static int count = 0;// 学生总数字段,用static修饰了
private String name;//姓名
private int sno;// 学号
public Student(String name, int sno) {
// 我们在每次该类初始化时,都将count+1
count++;
this.name = name;
this.sno = sno;
}
public Student() {
}
public static int getCount() {
return count;
}
public static void setCount(int count) {
Student.count = count;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSno() {
return sno;
}
public void setSno(int sno) {
this.sno = sno;
}
}
Main.java
package test06;
public class Main {
public static void main(String[] args) {
Student st1 = new Student("迷思爱", 12312);
Student st2 = new Student("学习乐园", 12313);
Student st3 = new Student("无道", 12314);
/*
* 此时count值:4
通过st1获取到的值:4
通过st2获取到的值:4
通过st3获取到的值:4
* */
System.out.println("此时count值:" + Student.count);
System.out.println("通过st1获取到的值:"+st1.count);
System.out.println("通过st2获取到的值:"+st2.count);
System.out.println("通过st3获取到的值:"+st3.count);
}
}
代码解释:
通过测试代码,可以发现:通过stX.count
获取到的值都是一样的,这证明:静态字段共享一个内存空间。
注意:
向上面的stX.count
的写法,是严重不推荐的,正确的写法是"类名.属性"(即上面的第一个println的写法)。
如果你用的是IDEA,你会发现,根本不会提示有count属性可用:
2. 静态方法
有静态字段,就有静态方法。用static修饰的方法称为静态方法。
如下,我们为Student添加一个静态方法,用以修改count的值:
package test06;
public class Student {
public static int count = 0;// 学生总数字段,用static修饰了
private String name;//姓名
private int sno;// 学号
public static void modify(int n) {
count = n;
}
// .... other functions..
}
测试:
public static void main(String[] args) {
Student st1 = new Student("迷思爱", 12312);
Student st2 = new Student("学习乐园", 12313);
Student st3 = new Student("无道", 12314);
Student.modify(10);
System.out.println("此时count值:" + Student.count);// 此时count值:10
}
静态方法也通过"类.方法名"调用,静态方法属于class
本身而不属于实例,因此,静态方法内部,无法访问this
变量,也无法访问实例字段,它只能访问静态字段。
同样,非静态方法,也无法调用静态方法;静态方法也无法调用该非静态方法;
静态方法经常用于工具类。例如:
- Arrays.asList()
- Math.random()
3. 接口的静态属性
前面章节我们说了接口只能有抽象方法,其实不准确;
接口中,我们也能定义字段:
public interface Animal {
public static int NUM = 0;
public static int AGE = 0;
}
但是,在接口中定义字段只能是常量(常量名我们一般大写!)
由于接口中定义字段只能是常量,所以如接口中的抽象方法一样,我们也可以简写(去掉多余修饰)
public interface Animal {
int NUM = 0;
int AGE = 0;
}
编译器会自动把该字段变为public static final
类型。
本节阅读完毕!
(分享)