不积跬步,无以至千里;不积小流,无以成江海。
Java语言基础
Java的引用传递(类关联、自身关联)
类关联实例:
有的人有汽车,有的人没有;
class Person { private String name; private int age; private Car car; //一个人有一辆车 public Person(String name, int age) { this.name = name; this.age = age; } public String getInfo() { return "姓名:" + this.name + "、年龄:" + this.age; } public void setCar(Car car) { this.car = car; } public Car getCar() { return this.car; } } class Car { private String name; private double price; private Person person; //一辆车属于一个人 public Car(String name, double price) { this.name = name; this.price = price; } public String getInfo() { return "汽车名字:" + this.name + "、汽车价格:" + this.price; } public void setPerson(Person person) { this.person = person; } public Person getPerson() { return this.person; } } public class Test { public static void main(String[] args) { // TODO Auto-generated method stub Person per1 = new Person("Jiang", 24); Car car1 = new Car("wow", 520.0); per1.setCar(car1); // 一个人有一辆车 car1.setPerson(per1); // 一辆车属于一个人 System.out.println(per1.getCar().getInfo()); // 从人找车 System.out.println(car1.getPerson().getInfo()); // 从车找人 } }
程序输出:
汽车名字:wow、汽车价格:520.0 姓名:Jiang、年龄:24
自身关联实例:
一个人会有孩子,孩子也有车。
class Person { private String name; private int age; private Car car; //一个人有一辆车 private Person children[]; public Person(String name, int age) { this.name = name; this.age = age; } public String getInfo() { return "姓名:" + this.name + "、年龄:" + this.age; } public void setCar(Car car) { this.car = car; } public Car getCar() { return this.car; } public void setChildren(Person children[]) { this.children = children; } public Person[] getChildren() { return this.children; } } class Car { private String name; private double price; private Person person; //一辆车属于一个人 public Car(String name, double price) { this.name = name; this.price = price; } public String getInfo() { return "汽车名字:" + this.name + "、汽车价格:" + this.price; } public void setPerson(Person person) { this.person = person; } public Person getPerson() { return this.person; } } public class Test { public static void main(String[] args) { // TODO Auto-generated method stub Person per1 = new Person("Jiang", 24); Person child1 = new Person("wen", 1); child1.setCar(new Car("mom", 1314)); per1.setChildren(new Person[] {child1}); Car car1 = new Car("wow", 520.0); per1.setCar(car1); // 一个人有一辆车 car1.setPerson(per1); // 一辆车属于一个人 System.out.println(per1.getCar().getInfo()); // 从人找车 System.out.println(car1.getPerson().getInfo()); // 从车找人 // 根据人找到所有的孩子以及汽车 for(int i = 0; i < per1.getChildren().length; i++) { System.out.println(per1.getChildren()[i].getInfo()); System.out.println(per1.getChildren()[i].getCar().getInfo()); } } }
程序输出:
汽车名字:wow、汽车价格:520.0 姓名:Jiang、年龄:24 姓名:wen、年龄:1 汽车名字:mom、汽车价格:1314.0