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
}
次に、最初のメソッドを作成しましょう。挨拶を表示する簡単なメソッドを作成します。このメソッドを main メソッドの外側と後、クラスレベルに追加します。
public class MethodDemo {
public static void main(String[] args) {
System.out.println("Welcome to the Method Demo!");
// TODO: Call methods here
}
// Add the new method here, outside and after the main method
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())を追加しました。これらのメソッドは現在の実装では車の状態を変更しませんが、より複雑なプログラムでは、速度や燃料レベルなどの属性を変更する可能性があります。
この例はオブジェクト指向プログラミングの力を示しています。私たちはデータ(メーカー、モデル、年)と動作(加速、ブレーキ、isAntique)の両方をカプセル化した Car クラスを作成しました。作成する各 Car オブジェクトは独立しており、独自の固有のデータセットを持っていますが、すべてのオブジェクトはクラスによって定義された同じアクションセットに従います。
"
I really Enjoy these hands on Labs . Once i get extra money i will be upgrading to the Pro version.
"
— Paul Ioannides
"
Really Impress with the creativity of "scenario" the skill is being asked to be used in. As is illistates the underlying reason of why this skill might be used in a "real world scenario""