一、Object类
java中,所有类都直接或间接继承自java.lang.Object类,可以说Object是java中所有类的祖先即根类
java中任何类都继承了Object类中的方法,主要有
toStrring()
public String toString() {
// TODO Auto-generated method stub
//return super.toString(); //默认打印包名+类内存地址
return "person meaage:" + name + address; //方法重写
}
System.out.println(s.toString());
/*
person meaage:xiaowei甲3214
*/
equals()
public boolean equals(Object arg0) {
// TODO Auto-generated method stub
//return super.equals(arg0); //默认比较的是地址
Person s = (Person)arg0; //强转
if(this.address == s.address && this.name == s.name){//比较成员变量
return true;
}else{
return false;
}
}
System.out.println(s.equals(s2));
/*
true
*/
hashcode()
clone()
getClass()
finalize()
二、代码演示
class Person{//class 相当于c语言的struct
String name;
String address;
public void printInfo(){
System.out.println("name=" + name);
}
private void printAddr(){
System.out.println("address=" + address);
}
public String toString() {
// TODO Auto-generated method stub
//return super.toString(); //默认打印包名+类内存地址
return "person meaage:" + name + address; //方法重写
}
public boolean equals(Object arg0) {
// TODO Auto-generated method stub
//return super.equals(arg0); //默认比较的是地址
Person s = (Person)arg0; //强转
if(this.address == s.address && this.name == s.name){//比较成员变量
return true;
}else{
return false;
}
}
}
public class Test {
public static void main(String[] args) {
Person s = new Person();
s.name = "xiaowei";
s.address = "甲3214";
Person s2 = new Person();
s2.name = "xiaowei";
s2.address = "甲3214";
System.out.println(s.equals(s2));
System.out.println(s.toString());
}
}
/*
true
person meaage:xiaowei甲3214
*/