System
2.1 System 类的概述
System包含几个有用的类字段和方法,他不能被实例化(直接类名调用)。
3.1 Object 类的概述
Object 是类层次结构的根,每个类都可以将Object类作为超类。所有类都直接或间接的继承自该类。
- 构造方法:public Object()
为什么说子类的构造方法默认访问的是父类的无参构造方法?
原因:因为他们的顶级父类只有无参构造方法。
package lib;
public class Student {
private String name;
private int age;
public Student(){
}
public Student(String name, int age) {
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;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
package lib;
public class ObjectDemo {
public static void main(String[] args) {
Student s = new Student();
s.setName("林青霞");
s.setAge(30);
System.out.println(s); //lib.Student@1540e19d
}
}
Student{name='林青霞', age=30}
建议所有子类重写toString()方法
3.2 Object类的常用方法
方法名 | 说明 |
---|---|
public String toString() | 返回对象的字符串表示形式。建议所用子类重写该方法,自动生成 |
public boolean equals(Object obj) | 比较对象是否相等。默认比较地址,重写可以比较内容,自动生成 |
package lib;
public class Student {
private String name;
private int age;
public Student(){
}
public Student(String name, int age) {
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;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
public boolean equals(Object o) {
//比较地址是否相同
if (this == o) return true;
//判断参数是否为空,判断两个对象是否来自同一个类
if (o == null || getClass() != o.getClass()) return false;
//向下转型
Student student = (Student) o; // student == s2;
if (age != student.age) return false;
return name != null ? name.equals(student.name) : student.name == null;
}
}
package lib;
public class ObjectDemo {
public static void main(String[] args) {
Student s1 = new Student();
s1.setName("林青霞");
s1.setAge(30);
Student s2 = new Student();
s2.setName("林青霞");
s2.setAge(30);
System.out.println(s1==s2); //false
System.out.println(s1.equals(s2)); // false
/*
*
* public boolean equals(Object obj) {
return (this == obj); //地址值不同,故为false
}*/
}
}
//最后结果:false true