所谓的引用就是指将堆内存空间的使用权交给多个栈内存空间。
自己打一遍代码,深入了解了引用的概念。
package Mycode;
public class TestStudent {
private String name;
private int age;
private Book book;
private TestStudent father;
public TestStudent(String name, int age) {
this.setName(name);
this.setAge(age);
}
public void setName(String n) {
name = n;
}
public void setAge(int a) {
age = a;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void setBook(Book b) {
book = b;
}
public Book getBook() {
return book;
}
public void setFather(TestStudent f) {
father = f;
}
public TestStudent getFather() {
return father;
}
public static void main(String[] args) {
TestStudent s = new TestStudent("张三", 30);
Book bk = new Book("葵花宝典", 38.6f);
TestStudent f = new TestStudent("张爸", 60);
Book fb = new Book("九阴真经", 44.6f);
s.setFather(f);
f.setBook(fb);
fb.setStudent(f);
s.setBook(bk);
bk.setStudent(s);
System.out.println("学生名" + s.getName() + ",年龄" + s.getAge() + ",他的书"
+ s.getBook().getTitle() + ",书的价格" + s.getBook().getPrice()
+ ",他爸" + s.getFather().getName() + ",他爸的书"
+ s.getFather().getBook().getTitle() + ",他爸的书的价格"
+ s.getFather().getBook().getPrice());
System.out.println("书名" + bk.getTitle() + ",价格" + bk.getPrice()
+ ",它的主人" + bk.getStudent().getName() + ",主人年龄"
+ bk.getStudent().getAge());
}
};
class Book {
private String title;
private float price;
private TestStudent student;
public Book(String title, float price) {
this.setTitle(title);
this.setPrice(price);
}
public void setTitle(String t) {
title = t;
}
public void setPrice(float p) {
price = p;
}
public void setStudent(TestStudent s) {
student = s;
}
public String getTitle() {
return title;
}
public float getPrice() {
return price;
}
public TestStudent getStudent() {
return student;
}
}