其他分享
首页 > 其他分享> > 封装的课堂练习

封装的课堂练习

作者:互联网

课堂练习
com.hspedu.encap: AccountTest.java 和 Account.java
创建程序,在其中定义两个类:Account和AccountTest类体会Java的封装性。
1.Account类要求具有属性:姓名(长度为2位3位或4位)、余额(必须>20)、
密码(必须是六位),如果不满足,则给出提示信息,并给默认值
2.通过setXxx的方法给Account的属性赋值。
3.在AccountTest中测试
提示知识点:
String name="";
int len = name.length(0)

 1 package com.test;
 2 public class Demo02 {
 3     public static void main(String[] args) {
 4 
 5     }
 6 }
 7 
 8 /**
 9     创建程序,在其中定义两个类:Account和AccountTest类体会java的封装性
10     1.Account类要求具有属性:姓名(长度为2位3位或4位)、余额(必须>20)、
11     密码(必须是六位),如果不满足,则给出提示信息,并给默认值
12     2.通过setXxx的方法给Account的属性赋值。
13     3.在AccountTest中测试
14  */
15 class Account{
16    public String name;
17    private  double money;
18    private  String  passWord;
19         //提供两个构造器
20     public Account() {
21     }
22     public Account(String name, double money, String passWord) {
23             this.setName(name);
24             this.setMoney(money);
25             this.setPassWord(passWord);
26     }
27 
28     public String getName() {
29             return name;
30     }
31     public void setName(String name) {
32         //名字长度设置
33             if (name.length()>=2&&name.length()<=4){
34                 this.name = name;
35             }else {
36                 System.out.println("您输入的名字过长....长度范围在2-4个");
37                 this.name="李飞";
38             }
39     }
40 
41     public double getMoney() {
42         return money;
43     }
44     public void setMoney(double money) {
45         //金额设置
46             if (money > 20) {
47                 this.money = money;
48             } else {
49                 System.out.println("您输入的金额不对....金额范围至少是20");
50                 this.money = 0;
51             }
52     }
53 
54     public String getPassWord() {
55         return passWord;
56     }
57     public void setPassWord(String passWord) {
58         //密码长度设置
59             if (passWord.length() == 6) {
60                 this.passWord = passWord;
61             } else {
62                 System.out.println("密码长度必须是6位。默认密码000000");
63             }
64     }
65     //显示相关信息
66     public  void  Info(){
67         System.out.println("姓名="+name+"\t"+"余额="+money+"\t"+"密码="+passWord);
68     }
69 }

用AccountTest去测试如下:

 1 package com.test;
 2 
 3 public class AccountTest {
 4     public static void main(String[] args) {
 5         //创建对象
 6         Account can = new Account();
 7         can.setName("smith");
 8         can.setMoney(30.0);
 9         can.setPassWord("123456");
10         can.Info();
11     }
12 }

 

标签:Account,封装,String,money,name,passWord,public,课堂练习
来源: https://www.cnblogs.com/nzm-2019/p/15967918.html