Question

How will i turn this code to encapsulation? They said encapsulation is data hiding, I know how to do some overloading and overriding, but not encapsulation, Please help me solve my problem. I'm not that good in Java Programming, Thank you in advance!

public class ATM {

public static void main(String[] args) {
   Scanner input = new Scanner(System.in);

   int bal = 1000;
   int balance =+ bal;

    System.out.println("===ATM Simulator===");
    System.out.println("\n[B] Balance");
    System.out.println("[W] Withdraw");
    System.out.println("[D] Deposit");
    System.out.println("[E] Exit");
    do{
    System.out.println("\nChoose Your Transaction:");
    String trans = input.next();
    try {
    if(trans.equalsIgnoreCase("W"))
    {
        System.out.println("Enter the Amount to Withdraw: [1000,500,200,100]");
        int wdraw = input.nextInt();
        int withd = wdraw;
        int charge = 10;
        if (withd%100==0)
        {
            balance = balance - withd - charge;
            System.out.println("Your current balance is now: "+balance);
        }
        else
        {
            System.out.println("Value Not in Range!");
        }
    }
    if(trans.equalsIgnoreCase("D"))
    {
        System.out.println("Enter the Amount to Deposit:");
        int deposit = input.nextInt();
        balance = balance + deposit;
        System.out.println("Your current balance is now: "+balance);
    }
    if(trans.equalsIgnoreCase("B"))
    {
        System.out.println("Your Current Balance is: "+balance);
    }

    if(trans.equalsIgnoreCase("E"))
    {
        System.out.println("Transaction Ended!\nThank you!");
        System.exit(0);
    }
        }
    catch (Exception e)
     {
         System.out.println("Invalid Input!");       
     }
    }
    while (balance>=200); 
}

}

Was it helpful?

Solution

Encapsulation is the approach of "hiding" the fields of a class so that they are only accessible through methods of the class (thus controlling what the fields can and cannot be set to)

See - http://www.tutorialspoint.com/java/java_encapsulation.htm

EG: if a class has a size field, you would make the size field private and then provide a setSize methods on the class - you can then add validation within the setSize method to control what the size can and cannot be set to

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top