所有类的父类—Object类
一。常用方法
1.1.toString( )方法
public class ObjectTest01 {
public static void main(String[] args) {
Student student =new Student("张三",110);
//重写toString之前
System.out.println(student.toString());//caopeng.javase.objectTest.Student@6bdf28bb
System.out.println(student);//caopeng.javase.objectTest.Student@6bdf28bb
//从上面的程序可以知道System.out.println(引用)会自动调用 引用.toString 方法
//并且输出的是 类名@对象的内存地址转换为十六进制的形式
//我们可以从写Object的toString方法
System.out.println(student);//Student{name='张三', no=110}
//通过查API帮助文档可知:SUN公司开发java语言的时候,建议所有的子类都去重写toString()方法。
}
}
class Student{
private String name;
private int no;
//构造方法
public Student() {
}
public Student(String name, int no) {
this.name = name;
this.no = no;
}
//set和get
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
//重写toString方法
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", no=" + no +
'}';
}
}
1.2 equals()方法
public class ObjectTest02 {
public static void main(String[] args) {
//在java语言中基本数据类型的比较我们可以使用"=="来比较
System.out.println("123 = 123 " + (123==123) );//123 = 123 true
//如果是java对象呢?
MyTime time1 = new MyTime(2020,4,8);
MyTime time2 = new MyTime(2020,4,8);
System.out.println("time1 = time2 " + (time1 == time2));//time1 = time2 false
//判断两个java对象是否相等,不能使用“==”,因为“==”比较的是两个对象的内存地址
//如果像比较字符串的方法 equals() 呢
System.out.println("time1 = time2 " + time1.equals(time2));//time1 = time2 false
//还是false,我们可以看一下Object的源码
/*发现 public boolean equals(Object obj) {
return (this == obj);
}*/
//equals底层使用的还是 == ,这不能满足我现在的想法
//所以重写 equals方法
System.out.println("time1 = time2 " + time1.equals(time2));//time1 = time2 true
}
}
class MyTime{
//属性
private int year;
private int month;
private int day;
//构造方法
public MyTime() {
}
public MyTime(int year, int month, int day) {
this.year = year;
this.month = month;
this.day = day;
}
//set 和 get
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public int getMonth() {
return month;
}
public void setMonth(int month) {
this.month = month;
}
public int getDay() {
return day;
}
public void setDay(int day) {
this.day = day;
}
//年月日相同就一样
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MyTime time = (MyTime) o;
return year == time.year &&
month == time.month &&
day == time.day;
}
}