引用传递应用实例

class Member{
    private int id;
    private String name;
    private Car car;//表示属于人的车
    public Member(int id,String name){
        this.id=id;
        this.name=name;
    }
    public String toString(){
        return "编号:" +  this.id + ",名字:" + this.name;
    }
    public void setCar(Car car){
        this.car  = car;
    }
    public Car getCar(){
        return this.car;
    }    
}
class Car{
    private String carName;
    private Member member;//人所拥有的车
    public Car(String carName){
        this.carName  = carName;
    }
    public String toString(){
        return "车的名字:" + this.carName;
    }
    public void setMember(Member member){
        this.member=member;
    }
    public Member getMember(){
        return this.member;
    }
}

public class Test{
    public static void main(String args[]){    
        //第一步添加人和车;
        Member m = new Member(10,"张三");
        Car c = new Car("法拉利");
        //第二步设置人和车的关系;
        m.setCar(c);//人拥有一辆法拉利
        c.setMember(m); //一辆车属于一个人
        //第三步:通过人找到车,通过车找到车主
        System.out.println(m.getCar());//通过m这个人找到他的车
        System.out.println(c.getMember());//通过c这个车找到其车主
    }
}

简单的一个代码来介绍引用传递的应用;

posted @ 2017-08-02 21:30  小洋编程  阅读(114)  评论(0编辑  收藏  举报