通過類與對象之間的引用傳遞來理解引用傳遞的機制
Person類
?
public class Person {
private int age ;
private String name ;
private Book book ;//一個人有一個書
private Person child ;//一個人有一個孩紙
public Person(int age, String name) { //構造函數(shù)
super();
this.age = age;
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Book getBook() {
return book;
}
public void setBook(Book book) {
this.book = book;
}
public Person getChild() {
return child;
}
public void setChild(Person child) {
this.child = child;
}
}
Book類
public class Book {
private String title ;
private double price ;
private Person person ; //一本書屬于一個人
public Book(String title, double price) {
super();
this.title = title;
this.price = price;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
}
RefTest類,測試主類
public class RefTest {
/**
* @param args
* 對象之間的引用傳遞
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Person per = new Person(30,"張三") ;
Person cld = new Person(10,"張草") ;
Book bk = new Book("JAVA開發(fā)實戰(zhàn)經(jīng)典",30.3) ;
Book b = new Book("一千零一夜",10.3) ;
per.setBook(bk) ;//設置兩個對象之間的關系,一個人擁有一本書
bk.setPerson(per) ;//設置兩個對象之間的關系,一本書屬于一個人
cld.setBook(b) ; //一個孩紙有一本書
b.setPerson(cld) ;//一個書屬于一個孩紙
per.setChild(cld) ;//一個人有一個孩子
System.out.println("從人找到書————————>姓名:"+per.getName()+",年齡:"+per.getAge()+",書名:"
+per.getBook().getTitle()+",價格:"+per.getBook().getPrice());
System.out.println("從書找到人————————>書名:"+bk.getTitle()+",價格:"+bk.getPrice()+",姓名:"
+bk.getPerson().getName()+",年齡:"+bk.getPerson().getName());
//通過人找到孩紙,并找到孩紙擁有的書
System.out.println(per.getName()+"的孩紙————>姓名:"+per.getChild().getName()+",年齡:"
+per.getChild().getAge()+",書名:"+per.getChild().getBook().getTitle()+
",價格:"+per.getChild().getBook().getPrice());
}
}
?