2.11、考虑一种关系(重点)
现在要求通过该类表示出如下的关系:
- 一个人有一本书,一本书属于一个人
按照类的划分,本句话可以划分出两个操作类:Person、Book
class Person {
private String name;
private int age;
private Book book; //一个人有一本书
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void setBook(Book book) {
this.book = book;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public Book getBook() {
return book;
}
}
class Book {
private String title;
private float price;
private Person person;
public Book(String title, float price) {
this.title = title;
this.price = price;
}
public void setTitle(String title) {
this.title = title;
}
public void setPrice(float price) {
this.price = price;
}
public void setPerson(Person person) {
this.person = person;
}
public String getTitle() {
return title;
}
public float getPrice() {
return price;
}
public Person getPerson() {
return person;
}
}
public class Demo02 {
public static void main(String args[]) {
Person per = new Person("张三", 30);
Book bk = new Book("java基础", 89.0f);
per.setBook(bk); //一个人有一本书
bk.setPerson(per); //一本书属于一个人
System.out.println(per.getBook().getTitle()); //有人找到其所拥有书的名字
System.out.println(bk.getPerson().getName()); //由书找到人的名字
}
};
进一步延伸
- 一个人不光有一本书,还可能有一个孩子,那么此种关系又该如何表示呢?
class Person {
private String name;
private int age;
private Book book; //一个人有一本书
private Person child;
public Person getChild() {
return child;
}
public void setChild(Person child) {
this.child = child;
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void setBook(Book book) {
this.book = book;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public Book getBook() {
return book;
}
}
class Book {
private String title;
private float price;
private Person person;
public Book(String title, float price) {
this.title = title;
this.price = price;
}
public void setTitle(String title) {
this.title = title;
}
public void setPrice(float price) {
this.price = price;
}
public void setPerson(Person person) {
this.person = person;
}
public String getTitle() {
return title;
}
public float getPrice() {
return price;
}
public Person getPerson() {
return person;
}
}
public class Demo02 {
public static void main(String args[]) {
Person per = new Person("张三", 30);
Person cld = new Person("李四", 10);
Book bk = new Book("java基础", 89.0f);
Book bkc = new Book("童话故事", 89.0f);
per.setBook(bk); //一个人有一本书
cld.setBook(bkc);
bk.setPerson(per); //一本书属于一个人
bkc.setPerson(cld);
System.out.println(per.getBook().getTitle()); //有人找到其所拥有书的名字
System.out.println(bk.getPerson().getName()); //由书找到人的名字
System.out.println(cld.getBook().getTitle());
System.out.println(bkc.getPerson().getName());
}
};
转载请注明来源