Java 的對象傳遞
java
舉一個簡單的例子說明一下
ide
需求:經過關聯兩個類,使能夠經過Person 對象獲取所關聯的 Car 類的對象中的數據函數
一個 Person 類,一個 Car 類,測試
==> Person 類this
class Person{ // 設置變量 private int pid; private String pname; private int page; private Car carname; // 多參構造方法 public Person(String pname, int page){ this.setPname(pname); this.setPage(page); } public String getInfo(){ return "姓名: " + getPname() + "\r" + "年齡:" + getPage() + "\r"; } public void setCarName(Car carname){ this.carname = carname; } public Car getCarName(){ return this.carname; } public void setPname(String pname){ this.pname = pname; } public String getPname(){ return this.pname; } public void setPage(int page){ this.page = page; } public int getPage(){ return this.page; } }
==> Car 類
spa
class Car{ private String cname; private Person pname; // 構造函數 public Car(String cname){ this.setCname(cname); } public void setPname(Person pname){ this.pname = pname; } public Person getPname(){ return this.pname; } public void setCname(String cname){ this.cname = cname; } public String getCname(){ return this.cname; } public String getCarInfo(){ return "車名:" + getCname(); } }
==> 測試類orm
public class testDemo { public static void main(String[] args) { Person p = new Person("Tom", 20); Car car = new Car("寶馬"); p.setCarName(car); car.setPname(p); System.out.println(p.getInfo()); // 經過 Person 對象獲取 其 Car 對象中的內容 System.out.println(p.getCarName().getCarInfo()); // 經過 Car 對象獲取 Person 對象中的內容 System.out.println(car.getPname().getPname()); } }