您的位置:首页 > 其它

第二十一天 引用传递深入

2012-09-18 10:53 155 查看

范例——进一步深入一对一关系

一个人有一个孩子,一个孩子有一本书
class Person01{
private String name;
private int age;
private Person01 child;
private Book book;
public Person01(String name, int age){
this.setName(name);
this.setAge(age);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Book getBook() {
return book;
}
public void setBook(Book book) {
this.book = book;
}
public Person01 getChild() {
return child;
}
public void setChild(Person01 child) {
this.child = child;
}
}
class Book{
private String title;
private float price;
private Person01 person01;
public Book(String title, float price){
this.setTitle(title);
this.setPrice(price);
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public Person01 getPerson01() {
return person01;
}
public void setPerson01(Person01 person01) {
this.person01 = person01;
}
}
class RefDemo05{
public static void main(String[] args) {
Person01 per = new Person01("张三",30);
Person01 cld = new Person01("张五",12);
Book bk = new Book("java开发实战经典", 12.5f);
Book cbk = new Book("舒克与贝塔",10.0f);

per.setBook(bk);
bk.setPerson01(per);

per.setChild(cld);
cbk.setPerson01(cld);
cld.setBook(cbk);

System.out.println("从人找到书名: \n 姓名:" + per.getName()
+ "; 年龄:" + per.getAge()
+ ";\n 书名:" + per.getBook().getTitle()
+ "; 价格:" + per.getBook().getPrice());
System.out.println("从书名找到人: \n 书名:" + bk.getTitle()
+ "; 价格:" + bk.getPrice()
+ ";\n 姓名:" + bk.getPerson01().getName()
+ "; 年龄:" + bk.getPerson01().getAge());
System.out.println(per.getName() + "的孩子: \n 姓名:" + per.getChild().getName()
+ "; 年龄:" + per.getChild().getAge()
+ "; \n 书名:" + per.getChild().getBook().getTitle()
+ "; 价格:" + per.getChild().getBook().getPrice());
}
}
运行结果:
从人找到书名:
姓名:张三; 年龄:30;
书名:java开发实战经典; 价格:12.5
从书名找到人:
书名:java开发实战经典; 价格:12.5;
姓名:张三; 年龄:30
张三的孩子:
姓名:张五; 年龄:12;
书名:舒克与贝塔; 价格:10.0
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  引用传递