Skip to main content

OOP Concept with Real Time Examples

A design philosophy is OOP. Object Oriented Programming is what it stands for. In contrast to outdated procedural programming languages, object-oriented programming (OOP) employs a separate set of programming languages. In OOP, everything is categorised as self-sustaining "objects". As a result, you achieve re-usability using the four core concepts of object-oriented programming. Programmes are organised around objects and data rather than action and logic in the object-oriented programming (OOP) paradigm. 

  Let's use your "Leg" as an example to grasp the object orientation clearly. The class "Leg" is one. Left and right legs are objects of type Leg on your body. A series of electrical impulses supplied through your body parts (through an interface) are what manage or control their primary functions. As a result, the body part serves as an interface between your body and your legs. The Leg is a well-designed class. The attributes of the Leg are modified slightly in order to produce the left Leg and the right Leg from it.

Now that we've covered the concepts,

Class
The foundation of any modern OOP language is the class. A class must be developed to represent data. a data structure that is defined by the user that groups methods and characteristics. A class is nothing more than a representation of an object type. The blueprint, plan, or template is what describes an object's specifics. The building block from which unique objects are produced is a class. Three elements make up a class: a name, characteristics, and operations. The class takes up no memory. It is a logical depiction of the data.

class Leg
{
}

Object
Object denotes a Class instance.The "new" keyword can be used to create objects.No memory will be used for class. As a result, in order to work with the data that the class represents, you must construct a variable for the class, often known as an object. 

When we create an object using the "new" keyword, heap memory is allocated for the class, and when we call an instance, the object's initial address is saved in the stack. When creating an object without using the new keyword, heap memory is not allocated. Objects in the stack have null values and no instances of the object will be created.  It is impossible to use an object to access a member of the class if it contains null.

Leg objLeg = new Leg(); 

In actuality, objects are useable instances of classes, whereas classes describe the nature of objects.
 
Struct and Class
Class is a reference type, whereas a structure is a value type.
Structure kept in a Stack Class kept in a Heap.
Inheritance is not supported by structures; only classes are.
For complex data structures, utilising a simple/small data structure class is a better option.
More than one interface can be implemented by a class or a structure. It is commonly known that a Struct can implement an interface and that boxing of a value type occurs when a value type is cast into an interface. 
Boxing as well as unboxing


Boxing: means converting value-type to reference-type.


Un-Boxing: means converting reference-type to value-type.


this Keyword
Every object has a "this" reference that points to the object itself.This keyword can be used to refer to the currently selected item. We may also use to explicitly call another constructor of the same class from one constructor.

Eg:
class Leg
{
   private string legname;
   private int number; 
 Student(string name, int num)
 {
   this.legname= name;
   this.number= num;
  } 
}



Abstraction

Abstraction is the process of concealing an object's operation and just displaying the information necessary for us to understand it. That is to say, it doesn't display ground details but yet conveys the main information. We include all relevant variables and methods in a class.

Eg: Employee and Patient.

Employer details, such as Name, Address, Qualification, DOB, Age, Mobile, Marks, and Experience, have to be filled out by the company.

The hospital is interested in receiving patient information such as name, date of birth, height, weight, age, address, phone number, blood type, etc.

Both the company and the hospital are eager to complete some standard fields, such as Name, Age, DOB, Address, and Mobile. Thus, an abstract class—a class made out of common objects—can be created. Although this class won't be complete, other classes may inherit from it.

Encapsulation: 

Encapsulation is the process of combining a method and a data member into a single entity (a class, for example). 

 Consider a capsule, for instance. The term "encapsulation" refers to the process of masking an object's interior workings, or its method of operation. This capsule contains a variety of items in a single unit. But we are unable to see what is in the side capsule. 

  This method is used to keep an object's information safe from other objects. Similar to variables, properties can also be set to private or public. We validate and set the property when we access it.

 We can continue with several further instances. My laptop. Although we can utilise laptops, we are unaware of the internal processes that take place. However, we can use that. similar to cellphone and TV

We can draw the conclusion that a collection of connected attributes, methods, and other members is handled as a single object.An abstract data type is another name for an encapsulated object.

There are numerous additional uses for encapsulation; one of these uses is the use of an interface. The information of a class that has been implemented can be hidden using the interface.

 //Declare as Private
private string _LegName;
// Property Set as publicpublic string LegName
{get{return _
LegName;
}set
{
_
LegName=value;
}


public class LegMain
{public static int Main(string[] args)
{
Leg L= new Leg();
d.
LegName="Right Leg";
Console.WriteLine("The Legis :{0}",d.
LegName);return 0;
}  


Note: Data can be protected against unintentional corruption using encapsulation. 

Constructor 

The constructor is a particular method of the class that is called automatically whenever an instance of the class is created.  

  
Constructors can be classified into five categories,
  1. Default Constructor
  2. Parameterized Constructor
  3. Copy Constructor
  4. Static Constructor
  5. Private Constructor 
Default Constructor : The term "default constructor" refers to a constructor that accepts no parameters. The default constructor has the drawback that all instances of the class will be initialised with the same values and that this cannot be changed.

Parameterized Constructor : A parameterized constructor is one that takes at least one parameter. The benefit of a parameterized constructor is that each instance of the class can have a distinct beginning value.

Class Leg()
{
  //default Constructor
        public Leg()
        {
            Name = "Left";
            Num = 2;
        }

  //Parametrized Constructor
        public Leg(string Name, int Num)
        {
            LegName = Name;
            LegNum = Num;
        }
}

 static void Main()
 {

  Leg L1 = new Leg();  //Default Constructor is called
  Leg L2= new Leg("Left",2);//Parametrized Constructor is called
        
        L1.Print();
        L2.Print();

     Console.Read();         
  }

Copy Constructor : Copy constructors are parametrized constructors that include a parameter of the same class type. Copy constructors are mostly used to initialize new instances with values from an existing instance.

  class Leg
    {
        string A;
        int B;
        public Leg(string I, int J)
        {
            A = I;
            B = J;
        }

        //Copy Constructor
        public Leg(Leg T)
        {
            A = T.A;
            B = T.B;
        }
     
        public void Print()
        {

            Console.WriteLine("{0}{1}", A, B);
        }
   

    }

 
  class CopyConstructor
    {
        static void Main()
        {         

            Leg L = new Leg ("Left", 2);

            //Invoking copy constructor
            Leg T1 = new Leg (L);
          
            L.Print();
            L1.Print();
            Console.Read();
        }
    }
Static Constructor : When a constructor is created as static, it will only ever be called once for all instances of the class, either when the first instance of the class is formed or when the first reference to a static member of the class is made. Initializing static fields in a class and writing code that only needs to be run once are done in the static constructor.

Private Constructor A constructor can also be made private. It is impossible to make an instance of a class when it has at least one private constructor. When a class has all of its members set to static, it cannot be instantiated because of the private constructor.
  • A class can have any number of constructors.
  • A constructor doesn’t have any return type even void.
  • A static constructor can not be a parameterized constructor.
  • Within a class you can create only one static constructor.
Destructor 
When a class instance is destroyed, a destructor, which is a particular method of the class, is automatically called. The code that must run while destroying an instance is written in the destructor. Create a method in the class bearing the same name as the class and beginning with the symbol ~.


Syntax :

~Leg()
{

}

What is the difference between the destructor and the Finalize() method? When does the Finalize() method get called?
 
The System's Finalise() function relates to the.Net Framework.Object type. The Finalise() method is implemented in C# by destructors. Both Finalise() and the destructor have the same functionality, in that they both provide code for allocating resources when the object is about to be garbage collected. When a programme is compiled in C#, destructors are changed to the Finalise() method. The.Net Runtime invokes the Finalise() method, and we are unable to forecast when this will happen. It is guaranteed to be called when the object is about to be garbage collected and there is no reference pointing to it.

Inheritance

There are numerous objects that can be specialised in the real world. A parent class in OOP has the ability to pass on its state and behaviour to its child classes. A is-a connection serves as the visual representation of this idea, which was created to govern generalisation and specialisation in OOP.
In OOP, parent and child classes are usually referred to by the OO words listed below:

  • Superclass: Parent class.
  • Subclass: Child class.
  • Base class: Parent class.
  • Derived class: Child class

  • Code becomes elegant and less repetitive because to inheritance.

    Syntax: 
    class child: parent   
    Types of Inheritance
    1. Single Inheritance
    2. Hierarchical Inheritance
    3. Multi Level Inheritance
    4. Hybrid Inheritance
    5. Multiple Inheritance

    The prospect of a child class having many parents is known as multiple inheritance. Humans have two parents by nature, thus a child will inherit traits from both parents. Single Inheritance A child can only have one class of parent, i.e. Hierarchical inheritance is the process of deriving more than one derived class from a single base class. Multi-level inheritance is the term used to describe when a derived class is produced from another derived class. Hybrid inheritance is any arrangement of single, hierarchical, and multiple levels.

    Sealed class

    A class that forbids inheritance is known as sealed. Some object model designs require to permit inheritance but prohibit the production of new instances; in this case, the class should be marked as sealed.

    In C#, the class declaration should be made as follows to establish a sealed class:

    sealed class Shape

    Polymorphism

    A class can be used as more than one type through inheritance; if it implements interfaces, it can also be used as any base type, any interface type, or its own type. Polymorphism is the term for this.

    Polymorphism refers to the existence of several forms. The implementation of polymorphism makes use of overloading and overriding. Compile time polymorphism, also known as early binding or static binding, and runtime polymorphism, sometimes known as late binding or dynamic binding, are two types of polymorphism.

    Overriding is when a class and its subclass share the same method names, arguments, and return types. The "override" keyword is used for overriding in C#. A method can be replaced with a new data-handling approach by overriding it.

    Overloading is when a method with the same name is called with different arguments; the return type may or may not be the same, depending on the class.

    Compile time Polymorphism or Early Binding

    Compile time polymorphism, often known as early binding, is the type of polymorphism where the compiler choose which polymorphic form to execute at compile time.

    Early binding has the benefit of quick execution. Due to lack of flexibility, as the compiler is aware of every aspect of the method during compilation.

    Overloaded operators, overloaded methods, and overridden methods that are invoked directly by using derived objects are a few examples of early binding.

    Runtime Polymorphism or Late Binding

    Runtime polymorphism, also known as late binding, is a type of polymorphism where the compiler choose which polymorphic form to execute at runtime rather than at compile time.

    Flexibility is a benefit of late binding, but execution will be slower since the compiler must obtain information about the method's execution at runtime.

    Overridden methods that are invoked using base class objects are an example of late binding.

    Class A
    {
          Virtual void Leg(string Name)
    {

    Class B:A
    {
      public overrid void Leg(String Name)
      {

      }
    }

    Example for Over loading

    Class A
    {
        class a()
       {
       }
       class a(String Name)
       {
       }
    }

    Alternatively stated, "Many forms of a single object is called polymorphism."

    Eg:


    A Team Leader behaves to Sub Ordinate.
    A Team Leader behaves to his/her seniors.
    A Team Leader behaves to other Team Leaders.
     
    The team leader in this instance is the object, but attitude varies depending on the circumstance. 


    Difference between Method Overriding and Method hiding

    A subclass can provide a customized implementation of a method that is already supplied by the base class by using method overriding. The base class's implementation is replaced (overridden) by the implementation in the subclass.
    When overriding, it's crucial to keep in mind that the method being overridden is connected to the method in the base class.
    The real type of the object to which the reference relates is used to determine which method implementation should be utilized when a virtual method is called on a reference. The version defined in the derived class is applied when a base class method is overridden in a subclass. This is so even should the calling application be unaware that the object is an instance of the derived class.

    Method hiding - There is no connection between the methods in the base class and derived class in terms of method hiding. The base class method is concealed by the derived class method.

    Sealed keyword can be used to prevent derived classes from overriding methods.
    The "sealed" keyword is unnecessary in this situation because all methods are sealed by default and will give you an error if you attempt to build a sealed method that is already sealed. However, if your method was designated as virtual in a base class, overriding it and designating it as "sealed" will stop derived classes from overriding it.

    Conclusion  

    OOP's features encourage you to keep working as the best programmer in the best programming language.





     

      

      

    Comments

    1. Hi, Nice description about Oops Concepts with real time examples.Thanks, its really helped me......

      -Aparna
      Theosoft

      ReplyDelete
    2. Its really helped me.. Thank you...

      ReplyDelete
    3. It's well explanation and also easy to understand for beginners like me....

      ReplyDelete

    Post a Comment

    Popular posts from this blog

    The key to achieving long-term success is a never-ending commitment to learning

    Success is a personal, complex idea that differs from person to person. It includes a sense of accomplishment, fulfilment, and personal development in addition to simple monetary or material gains. Success is the accomplishment of one's objectives, aspirations, or desired results, which are frequently consistent with one's morals and life's mission. It entails moving forward, conquering challenges, and consistently aiming to do better. Success can be found in many areas of life, such as work, relationships, self-improvement, health, and societal contribution. Success is ultimately a highly individualized endeavor that represents each person's particular goals and ideals. People can better traverse the constantly shifting landscape of technologies, market trends, and industry demands by obtaining new information and skills. It improves problem-solving skills, fosters adaptation, and creates possibilities for growth, all of which are important for both personal and profes

    Considerations to make before beginning software development

    Important guidelines for software architecture   Modularity, scalability, maintainability, reuse, and separation of concerns are some important aspects of software architecture. A good architecture should make the system easily testable, flexible, and extensible.  How to make a.NET application scalable   There are many ways to accomplish scalability, including:   1. Using a distributed architecture with load balancing and clustering.  2. Using caching tools to lessen database hits and boost performance.  3. Creating components with loose coupling and scalability in mind.  4. Making effective use of asynchronous programming techniques to manage multiple requests at once.  How to protect a.NET application's security   1. Implementing safe coding techniques, like as input validation and output encoding, can help to assure security in.NET applications.  2. Using techniques for authentication and permission that are based on roles or claims.  3. Transmission and storage of sensitive dat