引用传递是JAVA中最为核心的内容,也是实际开发中常见的一种操作
JAVA引用传递应用案例(简单demo)
/*
*创建people类,存储个人信息
*一个人可以拥有一本书,定义Book引用类型
*/
class People{
private String name;
private int id;
private Book book;
public People(String name, int id) {
this.name = name;
this.id = id;
}
public String getInfo() {
return "姓名:" + this.name + " 身份证:" + this.id;
}
public void setBook(Book book) {
this.book = book;
}
public Book getBook() {
return this.book;
}
}
/*
*创建Book类,存储书籍信息
*每本书可以被一个人拥有,定义People引用类型
*/
class Book{
private String name;
private double price;
private String author;
private People peo;
public Book(String name, double price, String author) {
this.name = name;
this.price = price;
this.author = author;
}
public String getInfo() {
return "书名:" + this.name + " 价格:" + this.price + " 作者:" + this.author;
}
public void setPeo(People peo) {
this.peo = peo;
}
public People getPeo() {
return this.peo;
}
}
程序主函数
public class javaDemo {
public static void main(String[] args) {
//声明对象初始化并建立关联
People people = new People("李明", 1027);
Book book = new Book("三体", 35.8, "刘慈欣");
people.setBook(book);
book.setPeo(people);
//根据关系获取数据
System.out.println(people.getBook().getInfo());
System.out.println(book.getPeo().getInfo());
}
}
System.out.println(people.getBook().getInfo());
people.getBook().getInfo() 该写法为代码链形式,写法等价于
// 相对于代码链来说,该方法较为繁琐
Book temp = people.getBook();
System.out.println(temp.getInfo());
所有代码复制到一个.java文件中,编译运行即可