public class Encapsulation {
public static void main ( String[ ] args ) {
Encapsulate obj = new Encapsulate( );
// Setting values of the variables
obj.setName( args[0] );
obj.setAge ( Integer.parseInt( args[1] ) );
obj.setRoll( Integer.parseInt( args[2] ) );
// Displaying values of the variables
System.out.print( obj.getName( ) + " " );
System.out.print( obj.getAge ( ) + " " );
System.out.print( obj.getRoll( ) );
// Error: Direct access of geekRoll is not possible due to encapsulation
// System.out.print( "Geek's roll: " + obj.geekName );
}
}
class Encapsulate {
// Private variables can only be accessed by public methods of class.
private String geekName;
private int geekRoll;
private int geekAge;
// Get method for age to access private variable geekAge
public int getAge( ) { return geekAge; }
// Get method for name to access private variable geekName
public String getName( ) { return geekName; }
// Get method for roll to access private variable geekRoll
public int getRoll( ) { return geekRoll; }
// Set method for age to access private variable geekage
public void setAge( int newAge ) { geekAge = newAge; }
// Set method for name to access private variable geekName
public void setName( String newName ) { geekName = newName; }
// Set method for roll to access private variable geekRoll
public void setRoll( int newRoll ) { geekRoll = newRoll; }
}
|