Practicing `static` Keyword
In this problem, you need to:
- Create a new private field called
totalCars
of typedouble
which tracks the total number of Car objects created; - Create a getter method called
getTotalCars
which simply returns the number of objects; - Make sure the value of the
totalCars
field is incremented every time a new Car object is created.
index.cs
1234567891011121314151617181920212223242526272829303132333435363738using 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()); } }
Var allt tydligt?
Tack för dina kommentarer!
Avsnitt 4. Kapitel 6
Fråga AI
Fråga AI
Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal
Suggested prompts:
Can you explain why the totalCars field should be static?
What would happen if totalCars was not static?
Can you show how getTotalCars is used in the Main method?
Awesome!
Completion rate improved to 2.04
Practicing `static` Keyword
Svep för att visa menyn
In this problem, you need to:
- Create a new private field called
totalCars
of typedouble
which tracks the total number of Car objects created; - Create a getter method called
getTotalCars
which simply returns the number of objects; - Make sure the value of the
totalCars
field is incremented every time a new Car object is created.
index.cs
1234567891011121314151617181920212223242526272829303132333435363738using 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()); } }
Var allt tydligt?
Tack för dina kommentarer!
Avsnitt 4. Kapitel 6