方法类型 | 调用方式 |
---|---|
静态方法 (static ) | 类名.方法名() 或 方法名() (在同一个类中) |
实例方法(非 static ) | 对象名.方法名() |
🚀 推荐记住:
- 如果方法是
static
,可以直接调用。 - 如果方法不是
static
,必须先创建对象,然后通过对象调用方法。
示例如下:
静态方法static的使用
import java.time.LocalDateTime;
public class Exercise {
public static void main(String[] args) {
while (true) { // 无限循环,不断检查秒数
int second = LocalDateTime.now().getSecond();
if (second % 5 == 0) { // 每 5 秒执行一次
System.out.println(isLightGreen());
}
try {
Thread.sleep(1000); // 让线程暂停 1 秒,防止 CPU 过载
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static String isLightRed() { // 改为 static
return "STOP";
}
public static String isLightGreen() { // 改为 static
return "GO";
}
public static String isLightYellow() { // 改为 static
return "SLOW";
}
}
实例方法的使用
import java.time.LocalDateTime;
public class Exercise {
public static void main(String[] args) {
Exercise exercise = new Exercise(); // ✅ 创建对象
while (true) { // 无限循环,不断检查秒数
int second = LocalDateTime.now().getSecond();
if (second % 5 == 0) { // 每 5 秒执行一次
System.out.println(exercise.isLightGreen()); // ✅ 通过对象调用
}
try {
Thread.sleep(1000); // 让线程暂停 1 秒,防止 CPU 过载
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public String isLightRed() { // 不再是 static
return "STOP";
}
public String isLightGreen() { // 不再是 static
return "GO";
}
public String isLightYellow() { // 不再是 static
return "SLOW";
}
}