Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Encapsulation Practice | OOP Principles
C# Beyond Basics
course content

Conteúdo do Curso

C# Beyond Basics

C# Beyond Basics

1. Additional Structures & File Handling
2. Structs & Enumerators
3. Introduction to Object-Oriented Programming (OOP)
4. OOP Essentials
5. OOP Principles

bookEncapsulation 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 and modelYear fields in Vehicle such that they are not accessible from outside the class, including derived classes;
  • Create a new method called getModelYear inside the Vehicle class such that it returns the modelYear. 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 and fuel properties should not be accessible from anywhere;
  • Make a method called getFuel which returns the value of fuel;
  • Make a method called addFuel which takes in a float argument called fuel. Inside the method, add the value of fuel to the property fuel (this.fuel).
cs

index

copy
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
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()}"); } }

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 5. Capítulo 7
some-alt