Encapsulation


  • Encapsulation is simply "the data protection". 
  • So encapsulation is used to protect data in variables.
  • We can restrict data by using the "private" modifier.
  • And then we can use get and set methods to access those data.
  • As variables are private,we should use public methods to access them.
  • In encapsulation,we access protected variables by using get and set methods.
eg :- class Book{
    private int number;
    private String name;
    private String author;
    }
    class Run{
    psvm(String[]args){
    Book b = new Book();
    b.number=12345;
    b.name="harry potter";
    b.author="J.K.Rowlin";
    }
    }

    public void setnum(int number){
    this.number=number;
    }
    public int getnum(){
    return number;
    }
    
    output - 12345

Comments

Popular posts from this blog

Variable and Method types in JAVA

Polymorphism

Casting