public class MethodDemo {
public static void main(String[] args) {
System.out.println("Welcome to the Method Demo!");
// TODO: Call methods here
}
// TODO: Add methods here
}
这是我们 Java 程序的基本结构。main 方法是程序开始执行的地方。
现在,让我们创建第一个方法。我们将编写一个简单的方法来打印问候语。将此方法添加到 main 方法之外,位于类的层级:
public class MethodDemo {
public static void main(String[] args) {
System.out.println("Welcome to the Method Demo!");
// TODO: Call methods here
}
// 在 main 方法之外添加新方法
public static void printGreeting(String name) {
System.out.println("Hello, " + name + "! Welcome to Java methods.");
}
}
public boolean isAntique() {
int currentYear = java.time.Year.now().getValue();
return (currentYear - year) > 25;
}
这个方法使用 Java 内置的 Year 类来获取当前年份。然后计算汽车的年龄,如果超过 25 年则返回 true,否则返回 false。
现在我们已经将这些方法添加到 Car 类中,让我们更新 CarDemo.java 文件以使用它们。打开 CarDemo.java 并将其内容替换为:
public class CarDemo {
public static void main(String[] args) {
Car myCar = new Car("Toyota", "Corolla", 2022);
Car classicCar = new Car("Ford", "Mustang", 1965);
myCar.displayInfo();
myCar.accelerate();
myCar.brake();
System.out.println(classicCar.getMakeAndModel() + " is an antique: " + classicCar.isAntique());
Car[] carArray = {myCar, classicCar};
for (Car car : carArray) {
System.out.println(car.getMakeAndModel() + " is an antique: " + car.isAntique());
}
}
}
Car Information:
Make: Toyota
Model: Corolla
Year: 2022
The Toyota Corolla is accelerating.
The Toyota Corolla is braking.
Ford Mustang is an antique: true
Toyota Corolla is an antique: false
Ford Mustang is an antique: true
恭喜!你已经显著扩展了 Car 类,并使用对象创建了一个更复杂的程序。这展示了如何使用面向对象编程在代码中模拟现实世界的概念。每个汽车对象现在都有自己的数据(制造商、型号、年份)和行为(加速、刹车等),就像真正的汽车一样。
我们向 Car 类添加了表示操作的方法(accelerate() 和 brake())。这些方法不会改变汽车的状态,但在更高级的程序中,它们可以修改速度或燃油量等属性。
We use cookies for a number of reasons, such as keeping the website reliable and secure, to improve your experience on our website and to see how you interact with it. By accepting, you agree to our use of such cookies. Privacy Policy