被同一类所有对象共享的修饰符
时间: 2023-08-22 13:39:38 浏览: 57
Java 中的 `static` 修饰符用于修饰类成员(类变量和类方法),表示该成员属于类而不属于任何一个对象,被所有同一类的对象共享。因此,`static` 修饰符也称为静态修饰符。
具体来说,使用 `static` 修饰的变量称为类变量(或静态变量),使用 `static` 修饰的方法称为类方法(或静态方法)。它们属于类本身,而不是某个对象的属性或方法。因此,可以通过类名直接访问类变量和类方法,而不需要先创建类的对象。
下面是一个使用 `static` 修饰符的例子:
```java
public class MyClass {
static int count; // 类变量
int id; // 实例变量
public MyClass() {
id = ++count; // 每次创建对象时,给 id 赋值为当前 count 值并将 count 自增 1
}
static void printCount() { // 类方法
System.out.println("Count: " + count);
}
void printId() { // 实例方法
System.out.println("Id: " + id);
}
public static void main(String[] args) {
MyClass obj1 = new MyClass();
MyClass obj2 = new MyClass();
obj1.printId(); // 输出:Id: 1
obj2.printId(); // 输出:Id: 2
MyClass.printCount(); // 输出:Count: 2
}
}
```
在上面的例子中,`count` 是一个类变量,被所有 `MyClass` 对象共享,用于记录 `MyClass` 对象的创建数量。每次创建对象时,都会将 `id` 赋值为当前 `count` 值并将 `count` 自增 1。`printCount()` 是一个类方法,用于输出 `count` 的值。`printId()` 是一个实例方法,用于输出当前对象的 `id` 值。在 `main()` 方法中,先创建两个 `MyClass` 对象,然后分别输出它们的 `id` 值。最后,通过 `MyClass.printCount()` 直接输出 `count` 的值。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)