对象一对一关系

来源:互联网 发布:中国为什么网络扫黄 编辑:程序博客网 时间:2024/05/22 14:23
package class1;
class Person {
private String name ;
private int age ;
private Book book ;
public Person(String name , int age){
this.setName(name) ;
this.setAge(age) ;
}
public void setName(String name) {
this.name = name ;
}
public void setAge(int age) {
this.age = age ;
}
public String getName() {
return this.name ;
}
public int getAge() {
return this.age ;
}
public void setBook(Book book) {
this.book = book;
}
public Book getBook() {
return book ;
}


}
class Book {
private String title ;
private float price ;
private Person person ;
public Book(String title,float price) {
this.setTitle(title) ;
this.setPrice(price) ;
}
public void setTitle(String title) {
this.title = title ;
}
public String getTitle(){
return this.title ;
}
public void setPrice(float price) {
this.price = price ;
}
public float getPrice() {
return this.price ;
}
public void setPerson(Person person) {
this.person = person ;
}
public Person getPerson() {
return this.person ;
}


}
public class RefDemo05 {
public static void main(String args[]) {
Person p = new Person("张三",30) ;
Book b = new Book("java",90.0f) ;
p.setBook(b) ;
b.setPerson(p);
System.out.println("从人找到书-->姓名:" + p.getName() + "; 年龄:" + p.getAge() + "; 书名:" + p.getBook().getTitle()
+ "; 价格:" + p.getBook().getPrice());
System.out.println("从书找到人-->书名:" + b.getTitle() + "; 价格:" + b.getPrice() + "; 姓名:" + b.getPerson().getName()
+ "; 年龄:" + b.getPerson().getAge());



}
}