+92 332 4229 857 99ProjectIdeas@Gmail.com

Encapsulation (Java)


Encapsulation (Java)
Encapsulation is the technique in which you hide the class members (variables) by declaring them to private so that they cannot be access out of the class except its public methods. It has the ability to change the implemented code dynamically.






For example
public class Student {
    private String name;
    private int rollNo;
        
        // Standard Setters
       public void setName (String _name) {
                   this.name = _name;
               }

       public void setRollNo (int _rollNo) {
                   if (_rollNo > 0) {          
                       this.rollNo = _rollNo;
                    } else {
                       this.rollNo = 100;
                   }              
               }
              
        // Standard Getters
       public String getName ( ) {
                  return name;
       }

       public int getRollNo ( ) {
                  return rollNo;
     }             
}     

You can see in above example that “id” and “name” are declared as private so you can only access them via their setters/getters.

0 comments: