对象一对多关系

package class1;
class Person {
private String name ;
private int age ;
private Book book ;
private Person child ;
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 ;
}
public Person getChild(){
return this.child;

public void setChild(Person child) {
this.child = child ;
}


}
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) ;
Person c = new Person("张草",10) ;

Book b = new Book("java",90.0f) ;

p.setBook(b) ;
b.setPerson(p);

c.setBook(b);
b.setPerson(c);

p.setChild(c);


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());
System.out.println(p.getName() + "的孩子-->姓名:"
+ p.getChild().getName() + "; 年龄:" + p.getChild().getAge()
+ "; 书名:" + p.getChild().getBook().getTitle() + "; 价格:"
+ p.getChild().getBook().getPrice());




}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值