+91-90427 10472
         
Dot net training in Chennai -Maria Academy

OOPs Concepts

17 Mar 2023

OOPs Concepts:

It is a programming paradigm that focuses on the use of objects to represent data and behaviors in software applications.

It is based on the concept of “classes” and “objects”.

The main principles of OOPs are Encapsulation, Inheritance, Polymorphism & Abstraction

Classes:
A class is a blueprint for creating objects. It defines the properties and methods that an object of that class will have. For example, a class called “Person” might have properties such as “name”, “age”, and “gender”, and methods such as “walk” and “talk”.

In C#, classes are a fundamental building block of object-oriented programming (OOP). A class is a blueprint or a template that defines the structure and behaviour of a particular type of object.

Here’s an example of a class in C#:

public class Person

{

    public string Name { get; set; }

    public int Age { get; set; }

    public string Address { get; set; }

    public void PrintDetails()

    {

        Console.WriteLine($”Name: {Name}, Age: {Age}, Address: {Address}”);

    }

}

In this example, we have defined a class called Person that has three properties: Name, Age, and Address. These properties are defined using auto-implemented properties, which are shorthand for defining a private field and public getter/setter methods.

The PrintDetails method is a behaviour of the Person class. It is a public method that can be called on an instance of the Person class to print out the person’s details.

To create an instance of the Person class and set its properties, we can do the following:

Person person = new Person();

person.Name = “John”;

person.Age = 30;

person.Address = “123 Main St.”;

And to call the PrintDetails method on the person instance:

person.PrintDetails(); // Output: Name: John, Age: 30, Address: 123 Main St.

In this way, classes in C# allow us to define the structure and behaviour of our objects and create instances of those objects with specific properties and methods.

Objects:

An object is an instance of a class. It represents a specific instance of the class and has its own set of values for the properties defined by the class. For example, an object created from the “Person” class might have a name of “John”, an age of 25, and a gender of “Male”.

In C#, an object is an instance of a class. When we create an instance of a class using the new keyword, we are creating an object of that class.

Here’s an example of creating an object of the Person class we defined earlier:

Person person = new Person();

In this example, person is an object of the Person class. We can access its properties and call its methods using the dot notation:

person.Name = “John”;

person.Age = 30;

person.Address = “123 Main St.”;

person.PrintDetails(); // Output: Name: John, Age: 30, Address: 123 Main St.

Each object of a class has its own set of properties and can have different values for those properties. For example, we can create another object of the Person class with different values for its properties:

Person person2 = new Person();

person2.Name = “Jane”;

person2.Age = 25;

person2.Address = “456 Elm St.”;

person2.PrintDetails(); // Output: Name: Jane, Age: 25, Address: 456 Elm St.

In this way, objects in C# allow us to create multiple instances of a class, each with its own set of properties and values. We can use these objects to represent real-world entities or concepts in our programs and manipulate them by calling their methods and accessing their properties.

Encapsulation:

One of the key features of OOP is encapsulation, which is the concept of bundling data and methods that operate on that data within a single unit. This makes it easier to manage and maintain the code and helps to prevent the data from being accessed or modified by code outside of the class.

Encapsulation is one of the core principles of object-oriented programming (OOP) and refers to the practice of bundling data and the methods that operate on that data within a single unit, called a class, and restricting access to the inner workings of that class from the outside world.

In C#, encapsulation is achieved through access modifiers, which are keywords that determine the level of access that other code has to a particular class member (i.e., fields, properties, methods). C# provides four access modifiers:

public: The member is accessible from any code.

private: The member is accessible only within the same class.

protected: The member is accessible within the same class and any derived classes.

internal: The member is accessible within the same assembly.

Here’s an example of using encapsulation to hide the implementation details of a Person class:

public class Person

{

    private string name;

    private int age;

    private string address;

    public string Name

    {

        get { return name; }

        set { name = value; }

    }

    public int Age

    {

        get { return age; }

        set { age = value; }

    }

    public string Address

    {

        get { return address; }

        set { address = value; }

    }

    public void PrintDetails()

    {

        Console.WriteLine($”Name: {Name}, Age: {Age}, Address: {Address}”);

    }

}

In this example, the fields name, age, and address are marked as private, which means they can only be accessed from within the Person class. However, we’ve also defined public properties Name, Age, and Address that provide access to these fields from outside the class. By using properties, we can control the access to the fields and add logic to the getter/setter methods if necessary.

The PrintDetails method is also a public method that can be called from outside the class to print out the person’s details. However, it does not provide direct access to the internal fields.

By using encapsulation in this way, we can ensure that the internal state of a class is not accidentally or intentionally modified from outside the class, and that changes to the internal implementation of the class do not affect the external code that uses it.

Inheritance:

Inheritance allows a new class to be based on an existing class, inheriting its properties and methods. This can save time and effort in development, as the new class can reuse the code of the existing class.

Inheritance is another core principle of object-oriented programming (OOP) and refers to the ability of a class to inherit properties and behaviours from a parent class. In C#, inheritance is achieved through the : symbol followed by the name of the parent class.

Here’s an example of using inheritance to create a Student class that inherits from the Person class:

public class Student : Person

{

    public int GradeLevel { get; set; }

    public string SchoolName { get; set; }

    public void PrintSchoolInfo()

    {

        Console.WriteLine($”School: {SchoolName}, Grade: {GradeLevel}”);

    }

}

In this example, the Student class inherits from the Person class using the: symbol. This means that the Student class has access to all of the public and protected members of the Person class, including its fields, properties, and methods.

In addition to the inherited members, the Student class defines two new properties, GradeLevel and SchoolName, and a new method, PrintSchoolInfo.

We can create an object of the Student class and set its properties just like we did with the Person class:

Student student = new Student();

student.Name = “John”;

student.Age = 15;

student.Address = “123 Main St.”;

student.GradeLevel = 9;

student.SchoolName = “High School”;

And we can call methods from both the Person and Student classes on the student object:

student.PrintDetails(); // Output: Name: John, Age: 15, Address: 123 Main St.

student.PrintSchoolInfo(); // Output: School: High School, Grade: 9

By using inheritance in this way, we can reuse code from existing classes and create more specialized classes that add new properties and behaviours on top of the existing ones. It also allows us to create a hierarchy of related classes, where each class builds on the properties and behaviours of the classes above it in the hierarchy.

Polymorphism:

Polymorphism allows objects of different classes to be treated as if they are of the same class, by using a common interface. This makes it easier to write code that works with multiple objects, as the code can be written to work with the interface rather than the specific classes.

Polymorphism is another core principle of object-oriented programming (OOP) and refers to the ability of objects of different classes to be used interchangeably in the same context. In C#, polymorphism is achieved through inheritance and interfaces.

There are two main types of polymorphism in C#: compile-time polymorphism and runtime polymorphism.

Compile-time polymorphism, also known as method overloading, refers to the ability of a method to have multiple definitions with different parameter lists. The correct method to call is determined at compile time based on the number and types of arguments passed to the method.

Here’s an example of method overloading in C#:

public class Calculator

{

    public int Add(int x, int y)

    {

        return x + y;

    }

    public float Add(float x, float y)

    {

        return x + y;

    }

}

In this example, the Calculator class defines two Add methods with different parameter types (int and float). Depending on the arguments passed to the Add method, the compiler will choose the appropriate overload at compile time.

Runtime polymorphism, also known as method overriding, refers to the ability of a subclass to provide a different implementation of a method that is already defined in its parent class. The correct method to call is determined at runtime based on the type of the object that the method is called on.

Here’s an example of method overriding in C#:

public class Animal

{

    public virtual void MakeSound()

    {

        Console.WriteLine(“The animal makes a sound.”);

    }

}

public class Dog : Animal

{

    public override void MakeSound()

    {

        Console.WriteLine(“The dog barks.”);

    }

}

In this example, the Animal class defines a virtual MakeSound method that can be overridden by its subclasses. The Dog class overrides the MakeSound method and provides a different implementation that prints “The dog barks.” to the console.

We can create objects of both the Animal and Dog classes and call the MakeSound method on them:

Animal animal = new Animal();

Dog dog = new Dog();

animal.MakeSound(); // Output: The animal makes a sound.

dog.MakeSound(); // Output: The dog barks.

By using polymorphism in this way, we can write code that is more flexible and adaptable to different types of objects, without having to know the exact type of the object at compile time. This makes our code more modular and easier to maintain over time.

Abstraction:

Abstraction is the concept of hiding unnecessary details and complexity from the user, while still providing the necessary functionality. This can make the code easier to use and maintain, as well as improve performance.

Abstraction is a core principle of object-oriented programming (OOP) that refers to the ability to hide the implementation details of a class from the outside world and expose only the relevant features and behaviours through a simplified interface. In C#, abstraction is achieved using abstract classes and interfaces.

An abstract class is a class that cannot be instantiated directly and can only be used as a base class for other classes. It may contain abstract methods, which are declared but not implemented in the abstract class. The subclasses of an abstract class must implement all its abstract methods to be instantiated.

Here’s an example of an abstract class in C#:

public abstract class Shape

{

    public abstract float GetArea();

}

In this example, the Shape class is declared as abstract, which means that it cannot be instantiated directly. It contains an abstract GetArea method, which is declared but not implemented in the abstract class.

Subclasses of the Shape class must provide their own implementation of the GetArea method in order to be instantiated. Here’s an example of a Rectangle class that extends the Shape class and implements the GetArea method:

public class Rectangle : Shape

{

    public float Width { get; set; }

    public float Height { get; set; }

    public override float GetArea()

    {

        return Width * Height;

    }

}

In this example, the Rectangle class extends the Shape class and provides its own implementation of the GetArea method, which calculates the area of a rectangle based on its width and height.

An interface is a contract that specifies a set of methods and properties that a class must implement. It does not contain any implementation code, but rather defines a set of public members that must be implemented by any class that implements the interface.

Here’s an example of an interface in C#:

public interface IPlayable

{

    void Play();

    void Pause();

    void Stop();

}

In this example, the IPlayable interface defines three methods (Play, Pause, and Stop) that must be implemented by any class that implements the interface.

Classes that implement the IPlayable interface must provide their own implementation of these three methods. Here’s an example of a MediaPlayer class that implements the IPlayable interface:

public class MediaPlayer : IPlayable

{

    public void Play()

    {

        Console.WriteLine(“Playing…”);

    }

    public void Pause()

    {

        Console.WriteLine(“Paused.”);

    }

    public void Stop()

    {

        Console.WriteLine(“Stopped.”);

    }

}

In this example, the MediaPlayer class implements the IPlayable interface and provides its own implementation of the Play, Pause, and Stop methods. Any class that implements the IPlayable interface can be used interchangeably with the MediaPlayer class in any context that requires an IPlayable object.

By using abstraction in this way, we can create classes that are more flexible, modular, and easier to maintain over time. We can also create a hierarchy of related classes and interfaces that define a set of common behaviours and features that can be reused and extended in different contexts.

Social tagging: > > > > > >