JAVA之间的引用传递

通过类与对象之间的引用传递来理解引用传递的机制

Person类

public class Person {
	private int age ;
	private String name ;
	private Book book ;//一个人有一个书
	private Person child ;//一个人有一个孩纸

	public Person(int age, String name) { //构造函数
		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开发实战经典",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());
	}

}

转载于:https://www.cnblogs.com/goforitjava/p/3680777.html

猜你喜欢

转载自blog.csdn.net/weixin_34273479/article/details/93333956