Course Content
C# Beyond Basics
C# Beyond Basics
Encapsulation Practice
The base code has two classes called Vehicle
and Car
. Some of the fields need to be hidden while some need to be exposed.
- Adjust the visibility of the
type
andmodelYear
fields inVehicle
such that they are not accessible from outside the class, including derived classes; - Create a new method called
getModelYear
inside theVehicle
class such that it returns themodelYear
. This method should be accessible from anywhere. This method will allow the users of this class to access the modelYear but not be able to modify it from outside; - The
ownerName
andfuel
properties should not be accessible from anywhere; - Make a method called
getFuel
which returns the value offuel
; - Make a method called
addFuel
which takes in afloat
argument calledfuel
. Inside the method, add the value offuel
to the propertyfuel
(this.fuel
).
index
using System; class Vehicle { // Edit code below this line public string type; public int modelYear; // Edit code above this line // Create a method below this line // Create a method above this line public Vehicle(string type, int modelYear) { this.type = type; this.modelYear = modelYear; } } class Car : Vehicle { // Edit code below this line public string brandName; public string numberPlate; public string ownerName; public float fuel; // Edit code above this line // Create a method below this line // Create a method above this line public Car(int modelYear, string brandName, string numberPlate, string ownerName, float fuel) : base("Car", modelYear) { this.brandName = brandName; this.numberPlate = numberPlate; this.ownerName = ownerName; this.fuel = fuel; } } class Program { static void Main() { // Create an instance of Car Car myCar = new Car(2022, "Toyota", "ABC123", "John Doe", 50.0f); // Accessing properties and methods from Car class Console.WriteLine($"Brand: {myCar.brandName}"); Console.WriteLine($"Number Plate: {myCar.numberPlate}"); // Accessing getModelYear method from Vehicle class Console.WriteLine($"Model Year: {myCar.getModelYear()}"); // Accessing getFuel method from Car class Console.WriteLine($"Fuel: {myCar.getFuel()}"); // Adding fuel using addFuel method myCar.addFuel(10.0f); Console.WriteLine($"After adding fuel, new Fuel: {myCar.getFuel()}"); } }
Thanks for your feedback!