Search⌘ K

Solution Review: Override a Method in the Derived Class

Explore how to override a method in a derived class in C#. Understand the use of the base keyword to call methods from the base class and combine them with derived class implementations, deepening your grasp of polymorphism concepts.

We'll cover the following...

Solution

C#
// Base Class
class Product {
// Private Data Members
private string _className;
public Product() { // Default Constructor
this._className = "Product";
}
// Getter Function
public virtual string GetName() {
return this._className;
}
}
// Derived Class
class XProduct : Product {
private string _className;
public XProduct(string className) { // Default Constructor
this._className = className;
}
// Overriden Method
public override string GetName() {
return base.GetName() + ", " +this._className;
}
}
class Demo {
public static void Main(string[] args) {
Product beverage = new XProduct("Beverage");
Console.WriteLine(beverage.GetName());
}
}

Explanation

...