Object是所有类的祖宗类,一般object里的方法调用都要被重写(因为原来的方法没什么用)
public class Student {
private String name;
private int age;
public Student() {
super();
// TODO Auto-generated constructor stub
}
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString () {//重写toString的方法
return "student{"+"name"+name+","+"age"+"="+age+"}";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override//按住ctrl+shift+s选中hashcode and equals自动生成此段代码
public boolean equals(Object obj) {
if (this == obj)
return true;//比较地址值,如果地址值相同,直接返回true,说明他们是一个值
if (obj == null)//如果传递出来的是空值那么肯定是false
return false;
if (getClass() != obj.getClass())//判断它们是否是同一个类,如果是不同类就返回false
return false;
Student other = (Student) obj;//向下转型,other = s2
if (age != other.age)//比较年龄
return false;
if (name == null) {//比较名字
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
import java.io.PrintStream;
public class Studentdemo {//其实后面有extends Object
public static void main(String[] args) {
Student s = new Student();
s.setName("林青霞");
s.setAge(19);
Student s2 = new Student();
s2.setName("林青霞");
s2.setAge(19);
System.out.println(s.equals(s2));
System.out.println(s);//Objectdemo.Student@15db9742
System.out.println(s.toString());//Objectdemo.Student@15db9742
/*public void println(Object x) {
String s = String.valueOf(x);
synchronized (this) {
print(s);
newLine();
}
}*/
/* public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
*/
}
}
输出:
true
student{name林青霞,age=19}
student{name林青霞,age=19}