Encapsulation Example Joseph Maldonado - acorrell5106/preAPCS-1516 GitHub Wiki

There Are Three Main Objectives For Encapsulation: a)To Hide Complexity. b)To Hide Sources of Change. c)To Protect Your Code But The Baseline Of The Concept Of Encapsulation Is To Make Your Program More Easy To Read,Add,Or Take Away From, For People Who Have Permission To Do So. For Example: Here Is A Program With Encapsulation:

ToolBox:

public class Encapsulation{
   private String StudentName;
   private String idNum;
   private int Age;
   public int getAge(){
      return Age;
   }
   public String getName(){
      return Name;
   }
   public String getIdNum(){
      return idNum;
   }
   public void setAge( int newAge){
      Age = newAge;
   }
   public void setName(String newName){
      Name = newName;
   }
   public void setIdNum( String newId){
      idNum = newId;
   }
}

This Encapsulation leads to your Main looking like this:

public class RunEncapsulation{

   public static void main(String args[]){
      Encapsulation encap = new Encapsulation();
      encap.setName("James");
      encap.setAge(20);
      encap.setIdNum("12343ms");
      System.out.print("Name : " + encap.getName()+ " Age : "+ encap.getAge());
    }
}

Instead of looking like this:

Different Main Thing:

import java.util.*;
public class NotEncap{
public static void main(String[]args);
String Age;
String Name;
String idNum;
Scanner input = new Scanner(System.in);
System.out.println("What will be your name?");
Name = input.nextLine();
System.out.println("How old are you?");
Age = input.nextLine();
System.out.println("What is Your id number");
idNum = input.nextLine();
System.out.println("Would you like to see your profile?");
String Decision = input.nextLine();
if(Decision.equalsIgnoreCase("No"){
System.out.println("Fine.");
}
if(Decision.equalsIgnoreCase("Yes"){
System.out.println("Age: "+Age+"  Name: "+Name+"  ID: "+idNum+" ");
}

You can see how much more code is being seen and exposed.