C#
C#
GROUP MEMBERS ID NO
SECTION: B
SUBMITTED TO: Haileyesus Tilahun
DUE DATE: DEC 13, 2024
• Virtual Method: The Refuel method in the Vehicle class is virtual, meaning it
provides a default implementation but can be optionally overridden in derived classes.
public virtual void Refuel()
{
Console.WriteLine($"{Name} is refueled.");
}
Analysis:
• Abstract methods enforce that derived classes must implement the method (Drive
is implemented in both Car and Bike classes).
• Virtual methods provide flexibility. The Refuel method has a default
implementation in Vehicle but is overridden in both Car and Bike classes for specific
behavior.
Code Context:
• Interface: IFuelEfficiency defines a contract with a single method:
public interface IFuelEfficiency
{
double GetFuelEfficiency();
}
• Abstract Class: Vehicle provides both fields (Name), constructors, and methods
(Drive and Refuel).
Analysis:
• Purpose: Interfaces define a contract that can be implemented by any class (e.g.,
Car implements IFuelEfficiency), while abstract classes provide a base structure with
shared logic and fields (Name in Vehicle).
• Use Case: The Car class inherits from Vehicle (abstract class) and implements
IFuelEfficiency (interface), showing how they can complement each other.
3. Override
Code Context:
The Car and Bike classes both override the Drive and Refuel methods from the Vehicle
class:
public override void Drive()
{
Console.WriteLine($"{Name} is being driven.");
}
public override void Refuel()
{
Console.WriteLine($"{Name} does not need refueling.");
}
Analysis:
• override keyword ensures that the method in the derived class (Car or Bike)
replaces the base class implementation (Vehicle) for that method.
• Importance: Overrides allow class-specific behavior while adhering to the base
class interface.
4. “Is-a” vs “Has-a”
Code Context:
• “Is-a”: Car and Bike inherit from Vehicle, meaning they are specialized types of
vehicles. This demonstrates an “is-a” relationship.
public class Car : Vehicle
public class Bike : Vehicle
5. Safe Castings
Code Context:
Safe casting is used with the is keyword in the Main method:
if (vehicle is Car castedCar)
{
Console.WriteLine($"Fuel Efficiency: {castedCar.GetFuelEfficiency()}
km/l");
}
Types of Casting:
• Upcasting: Assigning a derived class (Car) to a base class
reference (Vehicle):
Vehicle vehicle = car;
Why is it used?
• Upcasting allows treating objects uniformly (as Vehicle)
regardless of their specific type.
• Downcasting restores specific functionality (GetFuelEfficiency
from Car).
6. Extending vs Implementing
Code Context:
• Extending: Car and Bike extend the Vehicle class:
public class Car : Vehicle
Analysis:
• Extending allows inheriting shared behavior and properties from
a base class.
• Implementing provides a way to ensure a class adheres to a
contract defined by the interface (e.g., GetFuelEfficiency).