Tuesday, February 28, 2012

Encapsulation in Java

Assalamualaikum.
Today i will demonstrate how to use Encapsulation in Java.
EnCAPSULation = Capsule means it is data hiding.

It is 1 of 4 fundamental in OOP concept. The others are Inheritance, Polymorphism and Abstraction.
Google it to know more :)

In this tutorial we will create two java file

Customer.java
public class Customer {
    private String customerID;
    private String customerName;
    private String address;
    private int pinCode;
     
    public String getCustomerID() {
        return customerID;
        }
         
    public void setCustomerID (String myCustomerID) {
        customerID = myCustomerID;
        }

    public String getCustomerName(){
        return customerName;
        }
         
    public void setCustomerName (String myCustomerName){
        customerName = myCustomerName;
        }   

    public String getAddress () {
        return address;
        }
         
    public void setAddress(String myAddress) {
        address = myAddress;
        }
                 
    public int getPinCode(){
        return pinCode;
        }
     
    public void setPinCode(int myPinCode){
        pinCode = myPinCode;
        }
    }


EncapsulationTry.java
 public class EncapsulationTry{
 
    public static void main (String [] args){
    // Creating object of Customer Class
    Customer customer = new Customer();
 
    /* Calling setter methods for setting the values of instance variables */
    customer.setCustomerID ("0123");
    customer.setCustomerName ("MFZ");
    customer.setAddress ("Seremban,Negeri Sembilan, Malaysia");
    customer.setPinCode (70400);
    /* Calling getter methods for printing the values of instance variables */
 
    System.out.println ("Customer ID :" + " " + customer.getCustomerID());
    System.out.println ("Customer Name:" + " " +  customer.getCustomerName());
    System.out.println ("Customer Address:" + " " + customer.getAddress());
    System.out.println ("Customer Pin Code:" + " " + customer.getPinCode());
    }
}



Then compile all the java file and run the EncapsulationTry.class
Analyse the result and code, InsyaAllah you can get the point. 


  

No comments:

Post a Comment