Field Encapsulation Article Index for
Field
Limousines in
Field
Website Links For
Field
 

Information About

Field Encapsulation





public NormalFieldClass{

public String name ;


public static void main(String {Link without Title} args){

NormalFieldClass example1 = new NormalFieldClass() ;

example1.name = "myName" ;

System.out.println("My name is " + example1.name) ;
}
}

with the same example using encapsulation:

public EncapsulatedFieldClass{

private String name ;


public String getName(){
return name ;
}

public setName(String newName){
name = newName ;
}


public static void main(String {Link without Title} args){

EncapsulatedFieldClass example1 = new EncapsulatedFieldClass() ;

example1.setName("myName") ;

System.out.println("My name is " + example1.getName()) ;
}
}

In the first example a user is free to use the public ''name'' variable however they see fit - in the second however the writer of the class retains control over how the private ''name'' variable is read and written by only permitting access to the field via its ''getName'' and ''setName'' methods.