Powered by Blogger.

OOPs in Java - Definition of Encapsulation Example with Program

Definition of Encapsulation:-

Encapsulation is the technique of hiding some members of a class from other classes but provides a public interface to access that members.

General Definition:-

In general, encapsulation is one of the 4 fundamentals of OOP (object-oriented programming). Encapsulation is to hide the variables or something inside a class, preventing unauthorized parties to use. So the public methods like getter and setter access it and the other classes call these methods for accessing.

This mechanism is not unique to object-oriented programming. Implementations of abstract data types, e.g. modules, offer a similar form of encapsulation. This similarity stems from the fact that both notions rely on the same mathematical fundament of an existential.

Example of Encapsulation Program:

 class MyNumber{
   private int number;

   public void setNumber(int number){
     this.number=number;
   }

   public int getNumber(){
     return number;
   }
   }

   public class EncapTest{
     public static void main(String[]args){
       MyNumber my = new MyNumber();
       my.setNumber(45);
       System.out.println(my.getNumber());
   }
  }

At line 2, attribute number is a private member of MyNumber class, so this attribute will not be accessible form other classes. But from the EncapTest class we are accessing the number variable of MyNumber class using set and get methods of MyNumber class.

2 comments:

  1. I really enjoy the blog.Much thanks again. Really Great.
    Very informative article post. Really looking forward to read more. Will read on…


    oracle online training
    sap fico online training
    dotnet online training
    qa-qtp-software-testing-training-tutorial

    ReplyDelete
  2. I appreciate you sharing this article. Really thank you! Much obliged.
    This is one awesome blog article. Much thanks again.

    sap online training
    software online training
    sap sd online training
    hadoop online training
    sap-crm-online-training

    ReplyDelete