The IoT Academy Blog

What are the differences between polymorphism, encapsulation, and inheritance?

  • Written By  

  • Published on October 27th, 2022

Table of Contents [show]

 

Introduction

 

Object-oriented programming refers to a concept in high-level languages such as Java that uses objects and classes in its implementations. OOPs has three main building blocks: Polymorphism, Encapsulation, and Inheritance. Other paradigms of programming, such as procedural programming, require the sequential writing of programs. Java is a high-level, multi-paradigmatic programming language that supports both OOPs and procedural programming. The programmer decides which paradigm to use based on their expertise and the problems they are trying to solve. However, there is no dispute that OOPs facilitates, accelerate, dynamize, and secure programming. 

Java is currently the most widely used programming language in the world because of this.

Let's look at them now.

 

Inheritance

 

If you use the OOPs paradigm, codes are written in Java and Python as objects or blocks. Objects can interact with each other using each block's properties or by extending the block's functionality through inheritance. Inheritance ensures code reuse. A programmer can use millions of Java and Python libraries through inheritance. Other classes or methods may inherit from and add to a class's set of properties. A class might be of two different sorts. The first is the parent or base class, while the second is a child class that is capable of inheriting the parent class's properties. The cornerstone of object-oriented programming is inheritance. It is the process by which classes in OOPs languages like Java, Python, and others can inherit property from another class.

 

A parent class and a child class can both share the same properties. In DDL, a parent class implementation is demonstrated (Dynamic-link library). Different classes that can be used by other functions and programs can be found in DDL. Mother and kid are a real-world example of inheritance. A child can inherit height, voice patterns, and color attributes. Other children with the same traits can be born thanks to the mother.

 

The robot's mobility can be managed using a method or class called "Move Robot." Additionally, rather than having to continuously rewrite the code, you can construct methods and functions in other programs that can inherit the "Move Robot" class. You can also expand this class by inheriting it and adding new code to it that would tell the robot to move and trigger using an if and else statement depending on certain conditions. Code reuse can be achieved by using inheritance to construct many robots that would each take on the characteristics of the "Move Robot" parent class. Some traits from the parents may be present at birth in the child. Because many children can share the characteristics of their parents, inheritance ensures code reuse.

 

We look for a superclass that already includes the code or a portion of the code we wish to implement when we want to build a new function, method, or class. Then, we may create our class by deriving from the current class. We accomplish this in Java by utilizing the "Extends" keyword.

 

Our Learners Also Read: What Is Polymorphism in Java and How to Implement It?

 

Polymorphism

 

Polymorphism is made up of the two words poly and morph, where poly denotes quantity and morphs quality. Polymorphism is a characteristic of programming that permits a single interface for a broad category of operations. The pigeon is a bird by definition in the concept of birds and pigeons presented above. The pigeon falls under the category of flying birds if birds are further divided into various groups, such as flightless birds and flying birds. Additionally, the pigeon falls into the group of plant-eating animals if the class of animals is further divided into those that consume meat and those that do not. As a result, polymorphism is the idea that the same object can assume several forms.

 

Two Varieties of Polymorphism Exist:

 

Compile time polymorphism:

 

Static polymorphism is another name for it. Either operators or functions must be overloaded to produce this type of polymorphism. The compiler determines which method needs to be performed when we declare many methods with various signatures.

 

Runtime Polymorphism:

 

Additionally called Dynamic Method Dispatch. It is the procedure through which function calls to a method that has been overridden are handled at runtime. The Overriding technique is used to achieve this kind of polymorphism. The compiler is unaware that a method has been overridden when it is used in several contexts with the same set of parameters. It merely performs a simple existence check on the method and runs any runtime override routines.

We can upcast and downcast objects in Java. Polymorphism serves as this concept's fundamental tenet. Because it possesses the properties of a bird, the theory holds that a bird thing can have the value of a pigeon. Therefore, if both objects extend each other in the manner shown below, a parent object can also be initialized using child properties:

“`

Bird b = new Pigeon();

“`

 

Encapsulation

 

Encapsulation hides information within an object so it cannot be accessed directly from outside the object. This allows you to control how the data is used and prevents accidental data modification. For example, you might have a person's class with attributes such as name and age. You can then create methods to get and set these attributes. This would allow you to control how the data is used, and you could add validation to ensure that the data is valid before setting it.

Encapsulation is important because it helps keep your data safe. It also allows you to change the implementation of your code without affecting the rest of your codebase.

 

In a Nutshell, Encapsulation is:

 

  • Binding data to the code that manipulates it.
  • Keeps data and code safe from external interference

 

Looking at an example of a car power steering mechanism. A car's power steering is a complex system that internally has many components tightly connected together, working synchronously to turn the car in the desired direction. It even controls the power transmitted from the engine to the steering wheel. But only one interface is available to the outside world, and the rest of the complexity is hidden. In addition, the control unit is complete and independent in itself. No other mechanism is impacted by its operation.

 

The same encapsulation principle may be used to apply to code. The following qualities should be present in encapsulated code:

 

  • Everyone is aware of how to find him.
  • Regardless of the specifics of implementation, it is simple to use.
  • The code should not have any side effects on the rest of the application.
  • Encapsulation is to keep classes separate and prevent them from being tightly coupled.

 

An example of encapsulation is the java.util.Hashtable class. The user only knows that he can store data in the form of a key/value pair in a hashtable and that he can retrieve this data in various ways. But the actual implementation, such as how and where this data is stored, is hidden from the user. Users can simply use a Hashtable anywhere they want to store key/value pairs without bothering to implement it.

 

Inheritance

Encapsulation

Polymorphism

The method by which you can transfer the traits and behaviors of one class into another is called inheritance.

Encapsulation is the process of combining multiple pieces of data into a single class.

Whereas polymorphism is anything that has various definitions.

A child class (subclass) inherits all of the characteristics and methods from a parent class, according to the concept of inheritance (superclass).

According to encapsulation, one class cannot access the (private) data of another class.

Overloading and compile-time (polymorphism) decision-making on the function's implementation is made possible by polymorphism (overriding).

The example that follows shows how to implement inheritance in Java.

class Animal{ 

void eat(){

System.out.println("eating…");

class Dog extends Animal{ void bark(){

System.out.println("barking…");

class TestInheritance{ 

public static void main(String args[]){ 

Dog d=new Dog(); 

d.bark(); d.eat(); 

}

}

The example that follows shows how to implement encapsulation in Java.

public class EncapTest { 

private String name; 

private String idNum; 

private int age; 

public int getAge() { 

return age; 

public String getName() { 

return name; 

public String getIdNum() { 

return idNum; 

public void setAge( int newAge) { 

age = newAge;

 } 

public void setName(String newName) { 

name = newName; 

}

An easy illustration may be an animal from the actual world. Animal class and its specialized subclasses, like Cat and Dog, can exist in an application. These subclasses will replace the Animal class's default behavior as well as some of its own unique behavior.

 

public class Animal {

   public void makeNoise(){

       System.out.println("Some sound");

   }

}

class Dog extends Animal{

   public void makeNoise(){

       System.out.println("Bark");

   }

}

class Cat extends Animal{

   public void makeNoise(){

       System.out.println("Meawoo");

   }

}

 

 

 

Conclusion

 

 

Object-Oriented Programming's Fundamental Principles include simplicity, code reuse, extensibility, and security. Encapsulation, abstraction, inheritance, and polymorphism are used to accomplish these. The concept of inheritance relates to methods and functions that take on the properties of a different class. Code reuse is the key objective because it allows for quicker software development. DRY (don't Repeat Yourself) is an inheritance principle that states that distinct programs shouldn't contain similar codes. Instead, use a single class, call them via other methods, and extend the functions as necessary. Encapsulation is the practice of keeping classes secret so they cannot be changed by outside code, whereas polymorphism allows program code to have different meanings or functions.

 

About The Author:

logo

Digital Marketing Course

₹ 9,999/-Included 18% GST

Buy Course
  • Overview of Digital Marketing
  • SEO Basic Concepts
  • SMM and PPC Basics
  • Content and Email Marketing
  • Website Design
  • Free Certification

₹ 29,999/-Included 18% GST

Buy Course
  • Fundamentals of Digital Marketing
  • Core SEO, SMM, and SMO
  • Google Ads and Meta Ads
  • ORM & Content Marketing
  • 3 Month Internship
  • Free Certification
Trusted By
client icon trust pilot
1whatsapp