Object类是所有类的父类
Object类的常用方法
1.public String toString() 返回该对象的字符串表示
2.public boolean equals(Object obj) 指示其他某个对象是否与此对象“相等”
先讲toString()方法:
public class Person {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Person(String name) {
super();
this.name = name;
}
public static void main(String[] args) {
Person p=new Person("小明");
System.out.println(p);
System.out.println(p.toString());
}
}
运行结果
输出对象,默认调用的是toString()方法
这里我们通过修改toString()实现,来实现输出对象的结果
public class Person {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Person(String name) {
super();
this.name = name;
}
@Override
public String toString() {
return this.getName();
}
public static void main(String[] args) {
Person p=new Person("小明");
System.out.println(p);
System.out.println(p.toString());
}
}
运行结果
最后说下equals 是比较对象的引用,是否指向同一个堆内存(跟字符串的equals区别开)
public class Person {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Person(String name) {
super();
this.name = name;
}
public static void main(String[] args) {
Person p=new Person("小明");
Person p1=new Person("小明");
System.out.println(p.equals(p1));
}
}
运行结果
我们来重写下equals方法,来实现比较具体内容
public class Person {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Person(String name) {
super();
this.name = name;
}
@Override
public boolean equals(Object obj) {
String name=((Person)obj).getName();
return this.name==name;
}
public static void main(String[] args) {
Person p=new Person("小明");
Person p1=new Person("小明");
Person p2=new Person("小红");
System.out.println(p.equals(p1));
System.out.println(p.equals(p2));
}
}
运行结果