techmore.in

C# - Concrete Class

In C#, a concrete class is a regular class that can be instantiated and provides complete implementations for all of its methods. Unlike abstract classes or interfaces, a concrete class does not leave any method unimplemented, and you can create objects directly from it.

Key Features of Concrete Classes:

  1. Instantiable: You can create instances (objects) of a concrete class using the new keyword.
  2. Complete implementations: All methods in a concrete class are fully implemented, unlike abstract classes or interfaces.
  3. Inheritance: Concrete classes can inherit from abstract classes or other concrete classes and can implement interfaces.
  4. Can have fields, properties, methods, constructors, etc.: A concrete class can include all members such as fields, properties, methods, events, and constructors.

Syntax:

csharp
public class Dog { // Field private string name; // Constructor public Dog(string name) { this.name = name; } // Method public void Bark() { Console.WriteLine($"{name} is barking!"); } // Property public string Name { get { return name; } set { name = value; } } }

Example:

In the example below, Dog is a concrete class. You can create an instance of Dog and use its methods and properties.

csharp
Dog myDog = new Dog("Buddy"); // Create an instance of Dog myDog.Bark(); // Output: Buddy is barking! Console.WriteLine(myDog.Name); // Output: Buddy myDog.Name = "Max"; Console.WriteLine(myDog.Name); // Output: Max

Concrete Class Inheriting from an Abstract Class:

If a concrete class inherits from an abstract class, it must provide implementations for all abstract methods in the base class.

csharp
public abstract class Animal { public abstract void MakeSound(); // Abstract method (no implementation) public void Sleep() { Console.WriteLine("Sleeping..."); } } public class Cat : Animal { public override void MakeSound() // Implement the abstract method { Console.WriteLine("Meow!"); } }

Usage:

csharp
Cat myCat = new Cat(); myCat.MakeSound(); // Output: Meow! myCat.Sleep(); // Output: Sleeping...

Key Points:

  • Instantiable: Concrete classes can be directly instantiated, unlike abstract classes and interfaces.
  • Inheritance and Polymorphism: Concrete classes can inherit behavior from other classes and override methods to provide specific behavior.
  • Flexibility: Concrete classes can include any kind of member, making them very flexible for object-oriented programming in C#.