Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ チャレンジ:「static」キーワード | OOPの基本
C#オブジェクト指向構造

bookチャレンジ:「static」キーワード

メニューを表示するにはスワイプしてください

この課題では、以下を行う必要があります。

  • 作成されたCarオブジェクトの総数を追跡するための、型がtotalCarsの新しいプライベートフィールドdoubleを作成する。
  • オブジェクトの数を単純に返すゲッターメソッドgetTotalCarsを作成する。
  • 新しいCarオブジェクトが作成されるたびに、totalCarsフィールドの値がインクリメントされるようにする。
index.cs

index.cs

copy
1234567891011121314151617181920212223242526272829303132333435363738
using System; class Car { int modelYear; double mileage; string brandName; public Car(string brandName, int modelYear, double mileage) { this.brandName = brandName; this.modelYear = modelYear; this.mileage = mileage; // Write code below this line // Write code above this line } // Write code below this line // Write code above this line } class ConsoleApp { static void Main() { Console.WriteLine(Car.getTotalCars()); Car car1 = new Car("Toyota", 2022, 25.5); Car car2 = new Car("Honda", 2020, 30.2); Car car3 = new Car("Ford", 2021, 28.8); Console.WriteLine(Car.getTotalCars()); } }
  1. オブジェクト数を追跡するフィールドは常にデータを保持するため、staticである必要がある。
  2. アクセス修飾子の章で説明したように、ゲッターメソッドはプライベートフィールドの値を返すパブリックメソッドである。今回の場合、getTotalCarstotalCarsを返す必要がある。
  3. getTotalCarsメソッドもインスタンス化せずに使用したいため、staticである必要がある。
index.cs

index.cs

copy
123456789101112131415161718192021222324252627282930313233343536373839404142
using System; class Car { int modelYear; double mileage; string brandName; public Car(string brandName, int modelYear, double mileage) { this.brandName = brandName; this.modelYear = modelYear; this.mileage = mileage; // Write code below this line totalCars += 1; // Write code above this line } // Write code below this line private static double totalCars; public static double getTotalCars() { return totalCars; } // Write code above this line } class ConsoleApp { static void Main() { Console.WriteLine(Car.getTotalCars()); Car car1 = new Car("Toyota", 2022, 25.5); Car car2 = new Car("Honda", 2020, 30.2); Car car3 = new Car("Ford", 2021, 28.8); Console.WriteLine(Car.getTotalCars()); } }
すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 4.  6

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 4.  6
some-alt