qq:78080458 学习交流群:150633458
分类: Java
2013-10-30 21:34:01
函数的调用,java传参是传值,基本数据传递数据的拷贝,引用传递引用的拷贝
class Test
{
public static void change(int a, int b)
{
a = a + b;
b = a - b;
a = a - b;
}
public static void change(int[] num)
{
num[0] = num[0] + num[1];
num[1] = num[0] - num[1];
num[0] = num[0] - num[1];
}
public static void main(String[] args)
{
change(2,1); //传递数据的拷贝,交换失败
int[] num = new int{1,2};
change(num); //传递地址的拷贝,交换成功
}
Point pt;
System.oun.println(pt) 方法打印对象的时候,自动调用对象的toString方法,toString返回关于对象的描述字符串
Professor p1 = new Professor("zsls", 50);
Sdudent s1 = new Student("zhangsan", 20, p1);
Student s2 = (Student)s1.clone(); //克隆s1
s2.name = "lisi";
s2.age = 21;
s2.p1.name = "lsls";
s2.p1.age = 51;
System.out.println(s1.name + s1.age + s1.p1.name + s1.p1.age);
System.out.println(s2.name + s2.age + s2.p1.name + s2.p1.age); //s2是s1的克隆,不会修改s1的内容
}
class Point
{
int a,b;
public String toString() //覆盖toString方法
{
return "x=" +x "," + "y=" + y;
}
}
//对象的克隆,可以在传参的时候修改副本,而不修改对象本身
//克隆必须继承Cloneable接口,必须实现clone()方法,clone方法返回值是Object
class Professor implement Cloneable
{
String name;
int age;
Professor(String name, int age)
{
this.name = name;
this.age = age;
}
public Object clone() //方法的克隆
{
Object o = null;
try
{
o = super.clone();
}
catch(CloneNotSurpportedException e)
{
System.out.println(e.toString());
}
return 0;
}
}
class Student implement Cloneable //克隆必须实现Cloneable接口
{
String name;
int age;
Professor p;
Student(String name, int age, Professor p)
{
this.name = name;
this.age = age;
this.p = p;
}
public Object clone() //方法的克隆
{
Object o = null;
try
{
o = super.clone();
}
catch(CloneNotSurpportedException e)
{
System.out.println(e.toString());
}
o.p = p.clone(); //想要克隆外部类,必须在这里声明,而且外部类也满足克隆条件
return 0;
}
}