Object-Oriented Programming (Principles)

There are 4 major principles that make a language Object Oriented. These are Encapsulation, Data Abstraction, Polymorphism, and Inheritance. These are also called as four pillars of Object-Oriented Programming.

Encapsulation

Encapsulation is the mechanism of hiding of data implementation by restricting access to public methods. Instance variables are kept private and accessor methods are made public to achieve this.

For example, we are hiding the name and dob attributes of person class in the below code snippet.

Encapsulation — private instance variable and public accessor methods.

public class Employee {
    private String name;
    private Date dob;    
    public String getName() {
        return name;
    }    
    
    public void setName(String name) {
        this.name = name;
    }    
    
    public Date getDob() {
        return dob;
    }    
    
    public void setDob(Date dob) {
        this.dob = dob;
    }
}

Abstraction

Abstract means a concept or an idea which is not associated with any particular instance. Using abstract class/Interface we express the intent of the class rather than the actual implementation. In a way, one class should not know the inner details of another in order to use it, just knowing the interfaces should be good enough.

Inheritance

Inheritances expresses “is-a” and/or “has-a” relationship between two objects. Using Inheritance, In derived classes we can reuse the code of existing super classes. In Java, concept of “is-a” is based on class inheritance (using extends) or interface implementation (using implements).

For example, FileInputStream "is-a" InputStream that reads from a file.

Polymorphism

It means one name many forms. It is further of two types — static and dynamic. Static polymorphism is achieved using method overloading and dynamic polymorphism using method overriding. It is closely related to inheritance. We can write a code that works on the superclass, and it will work with any subclass type as well.

public class Calculate

{
    public void AddNumbers(int a, int b)
    {
        Console.WriteLine("a + b = {0}", a + b);
    }

    public void AddNumbers(int a, int b, int c)
    {
        Console.WriteLine("a + b + c = {0}", a + b + c);
    }

}

If you observe above “Calculate” class, we defined a two methods with same name (AddNumbers) but with different input parameters to achieve method overloading, this is called a compile time polymorphism in c#.

Last updated