Showing posts with label c# object oriented programming. Show all posts
Showing posts with label c# object oriented programming. Show all posts

Friday, April 2, 2021

What is Interface?

The interface is used to achieve abstraction in C#. It can only contain method declarations and properties. It is a contract between two entities. 

I am using the same example from the previous post on Abstraction, to know more about what is abstraction you can visit the same post.

interface IBird        //Interface keyword to declare it
{
    void Sound();    //Only method signature
}

Points to remember,
  • Like abstract classes, no instance creation so no constructor is allowed.is allowed for Interfaces as well 
  • Declaring interface with I comes out of practice to identify the same. 
  • Interfaces can contain methods and properties but not fields
  • All members of interface are abstract and public, you do not need to use public access modifiers
  • Derived classes must have an implementation of Interface members, you do not require to use override keyword to implement the method like abstract classes
  • The interface provides security and standard contract 

class Dove: IBird                    //Inherited Interface
{
        public void Sound()        //interface method implementation
        {               
                Console.WriteLine("Coo Coo");
        }
 }

above is an implementation example of Interface IBird to Dove class. 


Thursday, April 1, 2021

Polymorphism (Static vs Dynamic Polymorphism)

Polymorphism means "many forms", also can be said "one interface and many functions"

Inheritance allows the use of parent class members, Polymorphism makes the same methods work in a different way. Means method signature remains the same but the implementation may vary according to the need.

There are two forms we can achieve polymorphism

  • Static Polymorphism
    • compile time
  • Dynamic Polymorphism
    • run time

In, Static Polymorphism we have the same method with multiple definitions. Method parameters or return types must differ to achieve polymorphism. 

class Print
{
    public void PrintNumber(int 
val)
    {
            Console.WriteLine(
val);
    }

    public void PrintNumber(string val)
    {
            Console.WriteLine(val);
    }
}

The above example contains the same method PrintNumber() with different parameters, so here we client is able to pass either int to string to print the same. This is called static polymorphism.


In Dynamic Polymorphism, With the help of Abstract classes and Virtual methods, you can achieve dynamic polymorphism. As we know Abstract classes have an abstract method that would require to declare an implementation in derived classes.

Point to remember,

  • Instance creation is not allowed of an abstract class
  • Abstract methods can be defined in abstract classes
  • Sealed classes can not be inherited hence you can not declare an abstract class as Sealed.

abstract class Bird
{
        public virtual void Sound()
        {
                Console.WriteLine("Bird Sound");
        }
}

class Dove : Bird
{
       
 public override void Sound()
        {               
                Console.WriteLine("Coo Coo");
        } 
}

class Rooster : Bird
{
       
 public override void Sound()
        {               
                Console.WriteLine("cock-a-doodle-doo");
        } 
}

//Calling class method

Bird myBird = new Bird();        //This will create a bird object
Bird myDove = new Dove();    //This will create a dove object
Bird myRooster = new Rooster(); //This will create a rooster object

//Calling their methods

myBird.Sound();          //This returns Bird Sound from base class
myDove.Sount();        // This returns Coo Coo from the Dove class
myRooster.Sound();    //This returns cock-a-doodle-doo from Rooster class

The above example contains an abstract class Bird and Primary method definition with a virtual keyword which allows its child class to override the same method and make its own implementation. This is called a dynamic polymorphism as at runtime object comes to know which one to call. 

When to use Polymorphism?

  • This allows reusability in code 
  • The class extension is allowed using Inheritence so no change in the existing implementation
  • Respective clients have their own method definition so it won't affect existing clients

Wednesday, March 31, 2021

What is Inheritance in C#?

Inheritance is a relationship between a base and its derived class. 

  • Base class
    • Also called the Parent class
    • This can be reusable by being inherited to the child classes
  • Derived class
    • The child class inheriting its parent
Advantages of using Inheritance
  • Provides resubility of existing implementation
  • Polymorphism, will see more on dedicated post that helps the same
Example,

class Vehicle
{
    public string make;
    
    public void StartEngine
    {
        //Different ways, its implementation
    }

}

class Car : Vehicle         //class Car Inherits from Parent class Vehicle
{
    public string model;
}

Now class Car has its own property model and it has also inherited the properties from Vehicle class as used Inheritance.

So creating intance of the class will allow you to use both as given below,

Car myCar = new Car();
myCar.make = "Mercedes";          //Inherited property
myCar.model = "C Class";            //Own property
myCar.StartEngine();                     //Inherited method


Sealed keyword in C# restrict the Inheritance of the class. 
Example,

sealed class Vehicle
{
    //implementation
}

class Car : Vehicle    //This is not allowed due to sealed keyword
{
    //
implementation

Will see more on scenario base queries on Sealed keyword dedicated topic. 

Abstract Classes
  • It is a half defined class, becuase it can have an abstract implementation and hence no instance can be created of abstract classes
  • This is helpful to create a base class to provide primary implementation to be followed for their child classes
  • All the abstract methods declaration requires its child classes do have an implementation of the same
  • Virtual Methods helps child classes to Override the same and change their own logic 
Interface
  • It's a contract 
  • classes that inherite the interface must have to implement all the methods from that Interface
  • Instance creation is not allowed
  • Helps to standardize coding practice across multiple classes
Hide base class member
  • if parent and child classes share the same name for their methods, the new modifier at method definition helps to hide the base class implementation

C# Properties (Getter & Setters)

Encapsulation can be achieved using C# properties. Encapsulation means hiding a complex object from the outer world, in other words not exposing sensitive information to the client. 

For which we will require Private members and as that is not accessible to the outer world we initialize the values using Properties. 

Basically, Property contains two methods Get and Set. 

Example,

class Car
{
        private string model;                //Field member

        public string Model                  //Property
        {
              get
                {
                        return model;        //Get method
                }
                set

                {
                        model = value;        //Set method
                }
        }
}

Achieving encapsulation,

  • Provides control for the class members
  • Making fields read-only (Only get method) and write-only (Only set method)
  • Provides data security

Tuesday, March 30, 2021

What is Constructor?

Constructor is used to initializing the Class and Private members within the class. 

It is like a method but with no return type like void or int or any. Constructors are the first being called.


For example,

Class Car
{
        private string color; //Private field member


        public Car(string _color)    //Constructor initialization
        {
                color = _color;
        }

}


//Initializing Class

Car myCar = new Car("Red"); // This will call the constructor 

Basic things to remember,

  • It must match the class name
  • No return type is allowed
  • No separate method call required, as above example at class initialization it is called directly
  • All classes have their own default constructors if it is not declared.
  • Constructors can have multiple parameters and such is called Parameterized Constructors
  • Constructors can be overloaded by using different parameters (Will see more on Overloading and Overriding in upcoming posts)
Types of Constructors

  • Parameterless Constructor / Default Constructor
    • If no constructor is defined C# create for itself
  • Parameterized Constructor
    • Constructor with parameters one or many is called parameterized constructor
    • Used to initialize the members of the class
  • Static Constructor
    • Static constructor used to initialize the static members
    • You can have Public and Static constructor
  • Private Constructor
    • If a class has a Private Constructor only, other classes will not be able to create an instance of that class 

Monday, March 29, 2021

Class Members

 Class is a combination of its Fields and Methods and that is referred to Class Members

Class Car
{
        String Color;
        String Power;     

        Void Speed()
        {
            //Method Definition to calculate Max speed based on it's specifications
        }

}

Class Car consist of its member Color and Power and Speed() is a method. You can utilize the same object as many times as you need following the program need. Below is how you can create an object and initialize its members to required specification.

Car carObject = new Car(); //Creating Object of Class Car
carObject.Color = "Blue"; //Initializing fields
carObject.Power = 1000; //Initializing fields
carObject.Speed(); //Method Calling

There are acess modifiers used to restrict the usage of Class members, we will see it in upcoming post. Please stay connected. 

Working with Classes and Objects

I would request you to review my previous blog post for a basic understanding of Object Oriented Programming (To Read Click Me)

From the previous post, we will extend our Car example for better realistic understanding,

  • Class Car contains attributes such as color, engine power, size, airbag
  • Class Car contains methods such as drive, brake

Classes are just a blueprint. Objects are inherited property of the blueprint and it's reusable in nature.

Class example,

Class Car
{
        String Color;
        String Power;     

}

        From the above example, we have declared a class named Car and attributes are Color and Power. 

Creating an Object from the above class

Car carObject = new Car();

        Now, you can create as many as the object you want depending on the need of the program. This is called reusability. The below example explains the same.

        Car audi = new Car();
        
Car ferrari = new Car();


What is OOP (Object Oriented Programming)?

Object-Oriented Programming is about creating Objects out of Classes


What is a Class?

Class is nothing but a blue print or a template for an object. It contains the attributes and methods.

For example, Car is a class and Audi, Mercedes, Porche, Farrari are objects of it. 

What is an Object?

           An instantiation of the class creates and an Object. This helps to reduce the repetition of code.

For example, from above one Audi is an object created from a abstract Car class. 

Pillars of Object-Oriented Programming

  • Encapsulation

    • This means show only necessary to the outer world, achieved through Access Modifiers

  • Inheritance

    • Inheriting properties from a parent object makes it more reusable and extensible
    • Helps to remove redundant code

  • Polymorphism

    • Same method signature with various forms or taste
    • Dynamic Polymorphism
    • Static Polymorphism

  • Abstraction

    • This helps to hide the complexity in your code
    • Abstract classes and methods help to achieve multiple forms and are reusable in nature

Advantages of Object-Oriented Programming

  •  Reduce repetition of code
  •  Clear Code, Less Code
  •  Faster and manageable
  •  Easy to maintain, modify and debug
  •  Provides reusable application framework
  •  Rapid development

Do you have any questions? I would be glad to answer and help or make a dedicated post.

C# Interview Prep: 100 Common Questions for 0-3 Years Experience

Common C# Interview Questions  Basics of C# Language: What is C#? C# (pronounced C sharp) is a modern, object-oriented programming language...