引用传递实际应用

2020-10-12  本文已影响0人  曾梦想仗剑天涯

引用应用

//类关联结构
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;
  }
}
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;
  }
}
public class ArrayDemo {
  public static void main (String args []) {
   Person person = new Person("小明", 20);
   Car car = new Car("宾利", 8000000.0);
   person.setCar(car);
   car.setPerson(person);
   System.out.println(person.getCar().getInfo());
   System.out.println(car.getPerson().getInfo());
  }
}
//自身关联
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;
  }
}
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 setChildren(Person children []) {
    this.children = children;
  }
  public Person [] getChildren() {
    return this.children;
  }
  public void setCar(Car car) {
    this.car = car;
  }
  public Car getCar() {
    return this.car;
  }
}
public class ArrayDemo {
 public static void main (String args []) {
    Person person = new Person("小明", 20);
   Car car = new Car("宾利", 8000000.0);
   Person childA = new Person("张三", 10);
   Person childB = new Person("李四", 8);
   childA.setCar(new Car("BMW X1", 300000.0));
   childB.setCar(new Car("Audi R8", 2000000.0));
   person.setChildren(new Person [] {childA, childB});
   person.setCar(car);
   car.setPerson(person);
   System.out.println(person.getCar().getInfo());
   System.out.println(car.getPerson().getInfo());
   for(int x = 0; x < person.getChildren().length; x++) {
     System.out.println("\t|-" + person.getChildren()[x].getInfo());
     System.out.println("\t\t|-" + person.getChildren()[x].getCar().getInfo());
   }
  }
}
上一篇 下一篇

猜你喜欢

热点阅读