如何在java中编写封装代码

时间:2014-01-20 15:56:59

标签: java encapsulation

我如何将此代码转换为封装? 他们说封装是数据隐藏, 我知道怎么做一些重载 并且压倒一切, 但不是封装, 请帮我解决我的问题。 我在Java编程方面不是很好, 提前谢谢!

公共班级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); 
}

}

1 个答案:

答案 0 :(得分:0)

封装是"隐藏"类的字段,以便它们只能通过类的方法访问(从而控制字段可以和不能设置的内容)

请参阅 - http://www.tutorialspoint.com/java/java_encapsulation.htm

EG:如果某个类有size字段,您可以将size字段设为私有,然后在该类上提供setSize方法 - 然后您可以在setSize中添加验证控制大小可以和不能设置的方法