类与对象
就题来说
定义银行账户类Account,有属性:卡号cid,余额balance,所属用户Customer
银行账户类Account有方法:
(1)getInfo(),返回String类型,返回卡的详细信息
(2)取钱方法withdraw(),参数自行设计,如果取钱成功返回true,失败返回false
(3)存钱方法save(),参数自行设计,如果存钱成功返回true,失败返回false
Customer类有姓名、身份证号、联系电话、家庭地址等属性
Customer类有方法say(),返回String类型,返回他的个人信息。
在测试类ACTest中创建银行账户类对象和用户类对象,并设置信息,与显示信息
对于账户类:
public class Account {
//属性
int id;
int balance;
Customer customer;//Customer类类型(也是一种数据据类型<非基本数据类型>)
//构造函数初始化属性,非基本类型属性可以不用初始化
public Account(int id, int balance) {
this.id = id;
this.balance = balance;
}
//方法
//返回账号信息
public String getInfo() {//return的类容需要打赢就可以接收一下
return "账户所有者:"+customer.name+"账号:"+id+"余额"+balance;
}
}
同理可以得到客户类:
public class Customer {
String name;
int id;
int tel;
String address;
Account account;
public Customer(String name, int id, int tel, String address) {
this.name = name;
this.id = id;
this.tel = tel;
this.address = address;
}
public String say() {
return "姓名:"+name+id+tel+address+"账号:"+account.id;
}
}
测试类:
public class ACTest {
public static void main(String[] args) {
Account acc = new Account(1010, 100000);
Customer cus = new Customer("张超", 0201, 17605, "中南");
acc.customer = cus;
cus.account = acc;
System.out.println(acc.getInfo());
System.out.println(cus.say());
}
}
在这里面有几个注意点:
1.把之间定义的类作为属性,这样时可以的,那么数据类型就是定义的类的这种数据类型;
2.对于自己定义的类作为属性可以先定义好就行,具体的值在创建对象的时候再创建按,,然后用对象点属性就可以调用(得到)另外一个作为属性的类的对象的值。集体就像acc.customer = cus;这这样。
总结:1.后面对于这样的把类作为属性的还有很多,也是很常用的一种;
2.对于具体的属性再构造方法中暂时不能确定的属性可以先不写,在对象创建以后再赋给相应的属性值。