关于引用变量进行引用传递时传递变量为空和不为空的区别

/**
 * 
 */
/**   
 * @author jueying:   
 * @version 创建时间:2018-10-27 下午02:02:27   
 * 类说明   
 */
/**
 * @author jueying
 *
 */

class A {
	
	public int a;

	/**
	 * @return the a
	 */
	public int getA() {
		return a;
	}

	/**
	 * @param a the a to set
	 */
	public void setA(int a) {
		this.a = a;
	}
	
	

}


public class Test9 {
	
	A a;
	
	A a1;
	
	/*
	 * 
	*/
	public void fun(){
	    createA(a);	
	    System.out.println(a.getA());//java.lang.NullPointerException
	}

	public void createA(A b){//同理a指向的对象为空,那么b指向的对象也为空
		b=new A();//重新给b赋值指向新的对象
		b.setA(1);//b给新对象设置属性,但是引用变量a指向的对象任然为空,所以输出报空指针异常
	}
	
	
	
	
	public void fun1(){
		a1=new A();
		create(a1);	
		System.out.println(a1.getA());//输出1
	}
	
	//这里引用变量a1赋值给了引用变量b,b指向了a1引用的对象地址,通过b去改变对象的属性,那么a1指向的对象属性也发生改变
	public void create(A b){
		b.setA(1);
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
          
           new Test9().fun1();
           
           new Test9().fun();
           
          
	}

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值