You will learn followings:
- C# | Abstract Class
- C# | Interface
- C# | Encapsulation concepts
- C#| Polymorphism and Types
- C# | Inheritance
C# | Abstract Class
In this article we will explain you What is abstract Class in C#, its key area and benefits. We will discuss all with the help of example below. We can create an abstract class by decorating it with abstract keyword. Data abstraction is the process of hiding certain details and showing only essential information to the end user. This abstraction can only be achieved with either abstract classes or by using interfaces.
Features of abstract class.
- Abstract class always act a base class and is inherited by other classes.
- It can contain constructors and destructors.
- One cannot create an object of abstract class.
- Abstract class can never be static.
- Multiple inheritances is not supported in abstract class.
- Abstract class is used as a design concept in programming and provides a base upon which other classes are built.
- Abstract class can contain both abstract and non-abstract methods in it.
- All abstract method of abstract class must be implemented in child class.
- In C# we have “Abstract” keyword whereas in VB.NET abstract classes are created using “MustInherit” keyword.
- Abstract method does not have a body. Its body is provided or written in the derived class.
Code sample of abstract class
abstract class BankBaseClass // this is our abstract class
{
public abstract void insertData(); // abstract method
public abstract void updateData(); // abstract method
public abstract void deleteData(); // abstract method
public abstract void showData(); // abstract method
public void ValidateUser() // Non abstract method
{
Console.WriteLine("User validated successfully");
}
}
// ******* in following class we will inherit abstract class.******
public class Bank : BankBaseClass
{
// 'override' keyword is used to use base class methods as shown below
public override void insertData()
{
Console.WriteLine(“Insert data method is called”);
}
public override void updateData()
{
Console.WriteLine(“Update data method is called”);
}
public override void deleteData()
{
Console.WriteLine(“Delete data method is called”);
}
public override void showData()
{
Console.WriteLine(“Show data method is called”);
}
}
In above example we have taken an abstract class named "BankBaseClass". It contains abstract method and non-abstract method too. All abstract methods of abstract class need to be implemented in derived class named "Bank" and it must require implementing. Next 'override' keyword is used to use abstract class methods in the derived class as shown below:
public override void insertData()
{
Console.WriteLine(“Insert data method is called”);
}
Difference between Interface and Abstract class
- Abstract classes can have both abstract and non-abstract method whereas in Interface all methods are abstract by default.
- Multiple Inheritance in not feasible with abstract class but feasible with interfaces.
- In abstract classes "abstract" keyword is used and for interfaces we use "interface" keyword.
- We can have constructor in "abstract" class but not in interfaces.
- Abstract class can have static data members, but interfaces cannot.
- Performance of Abstract class is fast as compared to Interfaces.
- Abstract class can be implemented fully or partially but Interface are implemented fully.
What is the use of abstract class?
In nutshell we can say that an abstract class is used to provide a base for subclasses. It forces client class to use the same structure. For example, we have discussed one example above which have 4 abstract methods and client class must have to implement all these 4 methods, it will give same pattern to our multiple client classes, and this is for what abstract class is known as.
What is the difference between virtual and abstract methods?
Virtual: methods in abstract class can have its body and it provide the option to client class for implementation too. It depends upon user either to implement virtual method or not, but it does not force for implementation like abstract methods. Additionally, virtual methods can be created in abstract and non-abstract class.
Abstract: methods of abstract class do not have body and are forced to implement in the client class.
public abstract class A
{
public abstract void Method1();
public virtual void Method2()
{
// Default implementation which can be overridden by subclasses.
}
}
public class B:A
{
public override void Method1()
{
// You must have to override this method because it is abstract in above class.
}
public override void Method2()
{
// It is Virtual in base class, we can override this method
}
}
Can one Abstract class be inherited in another abstract class?
Yes, we can inherit one abstract class in another abstract class.
Can Abstract or Virtual methods be created as sealed?
Abstract and Virtual method cannot be crated as sealed. Abstract class always created as base class and is inherited by other classes, if it will be SALED then its actual behavior of inheritance will become useless. That is why it is not supported and if you'll forcefully add 'Sealed' in abstract methods then it will give compile time error as show in below image.
Can abstract class or abstract method be static?
No, an abstract method cannot be static. It will give compile time error. Additionally, default use of abstract method is that it needs to be override in derived class and it will not be feasible with static. Hence, it is not supportive in abstract class.
In this article we have explained you What is abstract Class, its characteristics and benefits. We hope this has cleared your doubt on Abstract class. For more information you can visit HERE.
For more information you can visit our C# Section for more such articles.
C# | Interface
Comparable as a Class, Interface can have methods, properties, events, and indexers as its individuals. But interfaces will contain just the declaration of the members. The implementation of the interface’s members will be given by class who implements the interface implicitly or explicitly.
Important points about interface:
- Interfaces specify what a class must do and not how.
- Interfaces can’t have private members.
- By default, all the members of Interface are public and abstract.
- The interface will always define with the help of keyword ‘interface‘.
- Interface cannot contain fields because they represent a particular implementation of data.
- Multiple inheritance is possible with the help of Interfaces but not with classes.
Syntax for Interface:
interface myInterface
{
// we can declare Events
// we can declare indexers
// we can declare functions/methods
// we can declare properties
}
Syntax for Implementing Interface:
class Student : myInterface
To announce an interface, utilize interface catchphrase. It is have utilized to supply add up to deliberation. Meaning all the individuals within the interface are announced with the purge body and are open and theoretical by default. A course that actualizes interface must execute all the functions/methods announced within the interface.
Example 1:
// working of interface
using System;
interface inter1
{
void display();
}
class student : inter1
{
public void display()
{
Console.WriteLine("I am in Code Config Sample program.");
}
// Main Method
public static void Main (String []args)
{
student t = new student();
t.display();
}
}
Output:
I am in Code Config Sample program.
Example 2:
// C# program to illustrate the interface
using System;
// interface declaration
interface Vehicle {
// all are the abstract methods.
void changeGear(int a);
void speedUp(int a);
void applyBrakes(int a);
}
class Bicycle : Vehicle{
int speed;
int gear;
public void changeGear(int newGear)
{
gear = newGear;
}
public void speedUp(int increment)
{
speed = speed + increment;
}
public void applyBrakes(int decrement)
{
speed = speed - decrement;
}
public void printStates()
{
Console.WriteLine("speed: " + speed + " gear: " + gear);
}
}
class Bike : Vehicle {
int speed;
int gear;
public void changeGear(int newGear)
{
gear = newGear;
}
public void speedUp(int increment)
{
speed = speed + increment;
}
public void applyBrakes(int decrement)
{
speed = speed - decrement;
}
public void printStates()
{
Console.WriteLine("speed: " + speed + " gear: " + gear);
}
}
class CodeCofig {
// Main Method
public static void Main(String []args)
{
Bicycle bicycle = new Bicycle();
bicycle.changeGear(2);
bicycle.speedUp(3);
bicycle.applyBrakes(1);
Console.WriteLine("Bicycle present state :");
bicycle.printStates();
Bike bike = new Bike();
bike.changeGear(1);
bike.speedUp(4);
bike.applyBrakes(3);
Console.WriteLine("Bike present state :");
bike.printStates();
}
}
Output:
Bicycle present state :
speed: 2 gear: 2
Bike present state :
speed: 1 gear: 1
Advantage of Interface:
- It is have used to achieve loose coupling.
- It is have used to achieve total abstraction.
- To achieve component-based programming
- To achieve multiple inheritance and abstraction.
- Interfaces add a plug and play similar as architecture into applications.
C# | Encapsulation concepts
Encapsulation is defined as the wrapping up of data and information under a single unit. It is the mechanism that binds together the data and the functions that manipulate them. In a different way, encapsulation is a protective shield that prevents the data from being accessed by the code outside this shield.
- Technically in encapsulation, the variables or data of a class are hidden from any other class and can be accessed only through any member function of its own class in which they are declared.
- As in encapsulation, the data in a class is hidden from other classes, so it is also known as data-hiding.
- Encapsulation can be achieved by: Declaring all the variables in the class as private and using C# Properties in the class to set and get the values of variables.
Example:
// C# program to illustrate encapsulation
using System;
public class DemoEncap {
// private variables declared
// these can only be accessed by
// public methods of class
private String studentName;
private int studentAge;
// using accessors to get and
// set the value of studentName
public String Name
{
get { return studentName; }
set { studentName = value; }
}
// using accessors to get and
// set the value of studentAge
public int Age
{
get { return studentAge; }
set { studentAge = value; }
}
}
// Driver Class
class GFG {
// Main Method
static public void Main()
{
// creating object
DemoEncap obj = new DemoEncap();
// calls set accessor of the property Name,
// and pass "Anmol" as value of the
// standard field 'value'
obj.Name = "
Anmol& quot;
;
// calls set accessor of the property Age,
// and pass "21" as value of the
// standard field 'value'
obj.Age = 36;
// Displaying values of the variables
Console.WriteLine(" Name : " + obj.Name);
Console.WriteLine(" Age : " + obj.Age);
}
}
Output:
Name: Anmol
Age: 36
Explanation:
In the above program, the "DemoEncap" class is encapsulated because the variables are declared private. To access these private variables, use the Name and Age accessors, which contain get and set methods to get and set the values of private fields. Accessors are defined as public, so they can be accessed by other classes.
Advantages of Encapsulation:
- Data Hiding: The user will have no idea about the inner implementation of the class. It will not be visible to the user that how the class is stored values in the variables. He only knows that we are passing the values to accessors and variables are getting initialized to that value.
- Increased Flexibility: We can make the variables of the class as read-only or write-only depending on our requirement. If we wish to make the variables as read-only then we have to only use Get Accessor in the code. If we wish to make the variables as write-only then we have to only use Set Accessor.
- Reusability: Encapsulation also improves the re-usability and easy to change with new requirements.
- Testing code is easy: Encapsulated code is easy to test for unit testing.
Encapsulation is a fundamental concept in object-oriented programming (OOP) that refers to the bundling of data and methods that process that data within a single unit. In C#, this is typically accomplished using classes.
The idea behind encapsulation is to hide the implementation details of a class from the outside world and expose only the public interfaces that allow users to interact with the class in a controlled and safe manner. This helps promote modularity, maintainability, and flexibility in the design of software systems.
To demonstrate encapsulation in C#, let’s consider the following example:
public class BankAccount {
private decimal balance;
public BankAccount(decimal initialBalance)
{
balance = initialBalance;
}
public void Deposit(decimal amount)
{
balance += amount;
}
public void Withdraw(decimal amount)
{
if (balance >= amount) {
balance -= amount;
}
else {
Console.WriteLine("Insufficient funds.");
}
}
public decimal GetBalance() { return balance; }
}
class Program {
static void Main(string[] args)
{
BankAccount myAccount = new BankAccount(1000);
myAccount.Deposit(500);
Console.WriteLine("Balance: "
+ myAccount.GetBalance());
myAccount.Withdraw(2200);
Console.WriteLine("Balance: "
+ myAccount.GetBalance());
}
}
Output:
Balance: 1500
Insufficient funds.
Balance: 1500
In this example, we have a class BankAccount that represents a simple bank account with a balance that can be deposited and withdrawn.
Balance fields are marked as private, meaning they cannot be accessed directly from outside the class. Instead, it provides public methods Deposit, Withdraw, and GetBalance that provide a controlled interface to the balance field.
In the Main method, create an object myAccount of the BankAccount class with an initial balance of 1000. Next, call the Deposit and Withdraw methods to change the balance, and call the GetBalance method to retrieve the current balance. Note that the balance field cannot be accessed directly but must be manipulated using public methods provided by the class.
I hope you enjoyed reading this post. For more information you can check out Microsoft learn.
For more information you can visit our C# Section for more such posts.
C#| Polymorphism and Types
Polymorphism means one name in many forms. This is the main feature of OOP. Polymorphism is the ability to take on multiple forms, but the name remains the same. There are two types of polymorphism.
- Compile Time Polymorphism
- Run Time Polymorphism
If you create two or more methods with the same name but different parameters or different parameter sequences and invocation times, the compiler determines which method to call based on the arguments specified at compile time. This is why it's called compile-time polymorphism. Also called static polymorphism. Implementation is done using overloaded methods and operators. The overloading process is called early binding. Regarding compile-time polymorphism, I have implemented the overloading concept using the example given below.
Example 1. See the following example. In that example, I have created two Add methods whose names are the same but whose parameters are different.
using System;
namespace DemoTest
{
class TestClass
{
public void Add(int a, int b)
{
int r = a + b;
Console.WriteLine("Add two integer Numbers = " + r);
}
public void Add(string x, string y)
{
Console.WriteLine("Concatenation two strings = " + x + y);
}
}
class Program
{
static void Main(string[] args)
{
// ***** add two integer values ****
TestClassaddClassObj = new TestClass();
Console.WriteLine("Enter Two Integer values");
int m = int.Parse(Console.ReadLine());
int n = int.Parse(Console.ReadLine());
addClassObj.Add(m, n);
// ***** add two string values *****
Console.WriteLine("Enter Two String values");
string s1 = Console.ReadLine();
string s2 = Console.ReadLine();
addClassObj.Add(s1, s2);
Console.ReadLine();
}
}
}
Run Time Polymorphism
Use runtime polymorphism when you want to create a method with the same name in an inherited class to override functionality in the base class. This is called runtime polymorphism because the compiler decides which method to call at runtime. This is achieved by using the virtual keyword within the method. To override a method in a base class, create the method in the base class as virtual and create the method in the derived class as an override.
Example 2. See the following example, where I have explained how we can override the base class method.
using System;
namespace DemoApp
{
class ClassA
{
public virtual void Show()
{
Console.WriteLine("This is Show from ClassA");
}
}
class ClassB : ClassA
{
public override void Show()
{
Console.WriteLine("This is Show from ClassB");
}
}
class ClassC : ClassA
{
public override void Show()
{
Console.WriteLine("This is Show from ClassC");
}
}
class Program
{
static void Main(string[] args)
{
ClassA classAObj = new ClassA();
classAObj.Show(); // It will call classA "Show" method
classAObj = new ClassB();
classAObj.Show(); // It will call ClassB "Show" method
classAObj = new ClassC();
classAObj.Show(); // It will call ClassC "Show" method
Console.ReadLine();
}
}
}
I hope you enjoyed reading this post. For more information you can check out Microsoft learn.
C# | Inheritance
Inheritance is a fundamental concept in object-oriented programming that allows us to define a new class based on an existing class. The new class inherits the properties and methods of the existing class and can also add new properties and methods of its own. Inheritance promotes code reuse, simplifies code maintenance, and improves code organization.
In C#, there are several types of inheritance:
In C#, there are 4 types of inheritance:
- Single inheritance: A derived class that inherits from only one base class.
- Multi-level inheritance: A derived class that inherits from a base class and the derived class itself becomes the base class for another derived class.
- Hierarchical inheritance: A base class that serves as a parent class for two or more derived classes.
- Multiple inheritance: A derived class that inherits from two or more base classes.
Here’s an example code that demonstrates each type of inheritance:
using System;
// single inheritance
class Animal {
public void Eat() {
Console.WriteLine("Animal is eating.");
}
}
class Dog : Animal {
public void Bark() {
Console.WriteLine("Dog is barking.");
}
}
// multi-level inheritance
class Mammal : Animal {
public void Run() {
Console.WriteLine("Mammal is running.");
}
}
class Horse : Mammal {
public void Gallop() {
Console.WriteLine("Horse is galloping.");
}
}
// hierarchical inheritance
class Bird : Animal {
public void Fly() {
Console.WriteLine("Bird is flying.");
}
}
class Eagle : Bird {
public void Hunt() {
Console.WriteLine("Eagle is hunting.");
}
}
class Penguin : Bird {
public void Swim() {
Console.WriteLine("Penguin is swimming.");
}
}
// multiple inheritance
interface I1 {
void Method1();
}
interface I2 {
void Method2();
}
class MyClass : I1, I2 {
public void Method1() {
Console.WriteLine("Method1 is called.");
}
public void Method2() {
Console.WriteLine("Method2 is called.");
}
}
// main program
class Program {
static void Main(string[] args) {
// single inheritance
Dog dog = new Dog();
dog.Eat();
dog.Bark();
// multi-level inheritance
Horse horse = new Horse();
horse.Eat();
horse.Run();
horse.Gallop();
// hierarchical inheritance
Eagle eagle = new Eagle();
Penguin penguin = new Penguin();
eagle.Fly();
eagle.Hunt();
penguin.Fly();
penguin.Swim();
// multiple inheritance
MyClass myClass = new MyClass();
myClass.Method1();
myClass.Method2();
Console.ReadLine();
}
}
Output
Animal is eating.
Dog is barking.
Animal is eating.
Mammal is running.
Horse is galloping.
Bird is flying.
Eagle is hunting.
Bird is flying.
Penguin is swimming.
Method1 is called.
Method2 is called.
Advantages of Inheritance:
- Code Reusability: Inheritance allows us to reuse existing code by inheriting properties and methods from an existing class.
- Code Maintenance: Inheritance makes code maintenance easier by allowing us to modify the base class and have the changes automatically reflected in the derived classes.
- Code Organization: Inheritance improves code organization by grouping related classes together in a hierarchical structure.
Disadvantages of Inheritance:
- Tight Coupling: Inheritance creates a tight coupling between the base class and the derived class, which can make the code more difficult to maintain.
- Complexity: Inheritance can increase the complexity of the code by introducing additional levels of abstraction.
- Fragility: Inheritance can make the code more fragile by creating dependencies between the base class and the derived class.
Reference book:
Here are some recommended books for learning about inheritance in C#:
- “C# 9.0 in a Nutshell” by Joseph Albahari and Ben Albahari: This book provides a comprehensive guide to C# 9.0, including inheritance, interfaces, and other object-oriented programming concepts.
- “Head First C#” by Jennifer Greene and Andrew Stellman: This book is a beginner-friendly introduction to C#, including inheritance and other object-oriented programming concepts.
- “Professional C# 7 and .NET Core 2.0” by Christian Nagel: This book is a comprehensive guide to C# 7 and .NET Core 2.0, including inheritance, polymorphism, and other object-oriented programming concepts.
These books are great resources for both beginners and experienced developers who want to learn more about inheritance in C#.
Inheritance is an important pillar of OOP(Object Oriented Programming). It is the mechanism in C# by which one class is allowed to inherit the features(fields and methods) of another class. Important terminology:
- Super Class: The class whose features are inherited is known as super class(or a base class or a parent class).
- Sub Class: The class that inherits the other class is known as subclass(or a derived class, extended class, or child class). The subclass can add its own fields and methods in addition to the superclass fields and methods.
- Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new class and there is already a class that includes some of the code that we want, we can derive our new class from the existing class. By doing this, we are reusing the fields and methods of the existing class.
How to use inheritance
The symbol used for inheritance is :. Syntax:
class derived-class : base-class
{
// methods and fields
.
.
}
Example: In below example of inheritance, class CCG is a base class, class CodeConfig is a derived class which extends CCG class and class Sudo is a driver class to run program.
// C# program to illustrate the
// concept of inheritance
using System;
namespace ConsoleApplication1 {
// Base class
class CCG {
// data members
public string name;
public string subject;
// public method of base class
public void readers(string name, string subject)
{
this.name = name;
this.subject = subject;
Console.WriteLine("Myself: " + name);
Console.WriteLine("My Favorite Subject is: " + subject);
}
}
// inheriting the CCG class using :
class CodeConfig : CCG{
// constructor of derived class
public CodeConfig()
{
Console.WriteLine("CodeConfig");
}
}
// Driver class
class Sudo {
// Main Method
static void Main(string[] args)
{
// creating object of derived class
CodeConfig g = new CodeConfig();
// calling the method of base class
// using the derived class object
g.readers("Aman", "C#.Net");
}
}
}
Output:
CodeConfig
Myself: Aman
My Favorite Subject is: C#.Net
Types of Inheritance in C#
Below are the different types of inheritance which is supported by C# in different combinations.
Single Inheritance:
In single inheritance, subclasses inherit the features of one superclass. In image below, the class A serves as a base class for the derived class B.
Multilevel Inheritance:
In Multilevel Inheritance, a derived class will be inheriting a base class and as well as the derived class also act as the base class to other class. In below image, class A serves as a base class for the derived class B, which in turn serves as a base class for the derived class C.
Hierarchical Inheritance:
In Hierarchical Inheritance, one class serves as a superclass (base class) for more than one subclass. In below image, class A serves as a base class for the derived class B, C, and D.
Multiple Inheritance (Through Interfaces):
In Multiple inheritance, one class can have more than one superclass and inherit features from all parent classes. Please note that C# does not support multiple inheritance with classes. In C#, we can achieve multiple inheritance only through Interfaces. In the image below, Class C is derived from interface A and B.
Hybrid Inheritance (Through Interfaces):
It is a mix of two or more of the above types of inheritance. Since C# doesn’t support multiple inheritance with classes, the hybrid inheritance is also not possible with classes. In C#, we can achieve hybrid inheritance only through Interfaces.
Important facts about inheritance in C#
- Default Superclass: Except Object class, which has no superclass, every class has one and only one direct superclass(single inheritance). In the absence of any other explicit superclass, every class is implicitly a subclass of Object class.
- Superclass can only be one: A superclass can have any number of subclasses. But a subclass can have only one superclass. This is because C# does not support multiple inheritance with classes. Although with interfaces, multiple inheritance is supported by C#.
- Inheriting Constructors: A subclass inherits all the members (fields, methods) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.
- Private member inheritance: A subclass does not inherit the private members of its parent class. However, if the superclass has properties(get and set methods) for accessing its private fields, then a subclass can inherit.
I hope you enjoyed reading this post. For more information you can check out Microsoft learn.
No comments:
Post a Comment