1.toString()方法
功能:
返回该对象的字符串表示。
源代码:
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
例:
不重写toString()方法时:
Student类:
package com.test.demoA;
public class Student {
String name;
int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
}
Test类:
package com.test.demoA;
public class Test {
public static void main(String[] args) {
Student student1 = new Student("张三", 20);
System.out.println(student1.toString());
}
}
运行结果为:
重写toString()方法时:
Test类不变。
Student类:
package com.test.demoA;
public class Student {
String name;
int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
运行结果为:
2.equals()方法
**功能:**指其他某个对象是否与此对象“相等”,默认情况下比较的是对象的引用是否相同。
源代码:
public boolean equals(Object obj) {
return (this == obj);
}
例:
不重写equals()方法时:
Student类:
public class Student {
String name;
int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
}
Test类:
public class Test {
public static void main(String[] args) {
Student student1 = new Student("张三", 20);
Student student2 = new Student("张三", 20);
boolean b = student1.equals(student2);
System.out.println(b);
}
}
运行结果为:
重写equals()方法时:
Test类不变。
Student类:
public class Student {
String name;
int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public boolean equals(Object obj1) {
Student obj2 = (Student) obj1;
if (this.name.equals(obj2.name) && (this.age == obj2.age))
return true;
else
return false;
}
}
运行结果为:
此时equals()方法比较的是内容而非地址。
3.clone()方法
功能:
复制对象。
不重写clone()方法无法实现克隆功能。
例:
Student类:
//实现Cloneable标识接口
public class Student implements Cloneable {
String name;
int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
//将protected改为public
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
Test类:
public class Test{
public static void main(String[] args) throws CloneNotSupportedException {
Student student1 = new Student("张三", 20);
Student student2 = (Student)student1.clone();//向下转型
System.out.println(student2.name);
System.out.println(student2.age);
}
}
运行结果为:
这里的克隆是浅克隆。