标签:
总所周知,Java语言风格类似C和C++,继承学习了C++语言的面向对象技术的核心,同时去除了C++语言的指针,改用引用(refrence)取代。那为什么要去除指针呢,改用引用,引用与指针又有什么区别呢?
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a = 3, b = 4;
swap(&a, &b);
printf("a = %d \n", a);
printf("b = %d ", b);
return 0;
}
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
通过指针能够方便并快速对变量进行底层操作,非常方便,使代码非常简洁,但是指针太灵活,太强大,很容易造成内存泄漏和产生off-the-end指针。利用指针编写的程序也更容易隐含各式各样的错误,同时程序的可读性也会大打折扣。所以Java去除了指针,而采用更加安全可靠的引用。
Object o; //这里是在堆栈中的创建的句柄(Handle) o = new Object(); //在堆中创建对象,并使句柄指向该对象
引用或句柄相当于电视机的遥控器,对遥控器操作,就能操作电视机,实际上,但我们按下”调小音量“,我们实际上操作的是遥控器,再有遥控器操作电视机,等价于直接操作电视机。当我们到处走走的话只需拿着遥控器即可,无需拿着电视机。引用是引用对象的遥控器,我们不能直接操作对象,只能通过引用进行操作。
package com.cang.refrence;
public class TestPrimitive {
public static void main(String[] args) {
int a = 3, b = 4;
System. out.println( "Before swap the a and b: a = " + a + ",b = " + b);
swap( a, b);
System. out.println( "After swap the a and b: a = " + a + ",b = " + b );
}
public static void swap( int a, int b) {
int temp = a;
a = b;
b = temp;
}
}
运行结果:


public class TestRefrence {
public static void main(String[] args) {
StringBuffer buffer= new StringBuffer( "colin");
SChange( buffer);
System. out.println( buffer);
}
public static void SChange (StringBuffer str) {
str= new StringBuffer( "huang");
}
}
结果:colin

public class TestRefrence2 {
public static void main(String[] args) {
StringBuffer buffer= new StringBuffer( "colin");
SChange( buffer);
System. out.println( buffer);
}
public static void SChange (StringBuffer str) {
str.append( "huang");
}
}
结果:colinhuang

标签:
原文地址:http://www.cnblogs.com/codingexperience/p/4657475.html