把属性和方法封装在一起,数据被保护在内部,程序的其他部分只通过被授权的方法,才能对数据进行操作
package encap; public class Account { private String name; private double balance; private String password; @Override public String toString() { return "Account{" + "name='" + name + '\'' + ", balance=" + balance + ", password='" + password + '\'' + '}'; } public Account(String name, double balance, String password) { this.setBalance(balance); this.setName(name); this.setPassword(password); } public String getName() { return name; } public void setName(String name) { if (name.length() >= 2 && name.length() <= 4){ this.name = name; }else System.out.println("名字长度应在2-4,以自动选择默认值"); this.name = "李华"; } public double getBalance() { return balance; } public void setBalance(double balance) { if(balance >= 20){ this.balance = balance; }else { this.balance = 20; } } public String getPassword() { return password; } public void setPassword(String password) { if (password.length() == 6){ this.password = password; }else { this.password = "666666"; } } }
package encap; public class AccountTest { public static void main(String[] args) { Account account = new Account("nacy",200,"123456"); Account account1 = new Account("lllll",0,"124"); System.out.println(account.toString()); System.out.println(account1.toString()); } }
结果
名字长度应在2-4,以自动选择默认值
Account{name=‘李华’, balance=200.0, password=‘123456’}
Account{name=‘李华’, balance=20.0, password=‘666666’}