文章目录
1.Java面向对象进阶
1.1Object类
Object 是 JDK 提供的一个类,位于 java.lang 包中,该类是Java 中所有类的直接父类或间接父类,Java 中的每一个类都是 Object 类的派生类。
这些方法都是Object类提供的
package entity.pojo;
public class Account {
public void test() throws Exception{
hashCode();
toString();
getClass();
equals(null);
clone();
notify();
notifyAll();
wait();
wait(100L);
wait(100L,100);
}
}
1.2重写Object类方法
经常被重写的方法
- toString:以字符串的形式来返回某个类的实例化对象信息
- equals:判断两个对象是否相等
- hashCode:返回对象的散列码
toString
原始的toString
public String toString() {
return getClass().getName() + "@" +Integer.toHexString(hashCode());
}
重写之后toString()
@Override
public String toString() {
return "User{" +"id=" + id +", name='" + name + '\'' +'}';
}
equals
原始的equals
public boolean equals(Object obj) {
return (this == obj);
}
String中对equals方法的重写
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString =(String)anObject;
int n = value.length;
if (n == anotherString.value.length) {
char v1[] = value;
char v2[] = anotherString.value;
int i = 0;
while (n-- != 0) {
if (v1[i] != v2[i])
return false;
i++;
}
return true;
}
}
return false;
}
hashCode
原始的hashCode
public native int hashCode();
本地方法:Java 无法访问操作系统底层,C++ 写的一套程序,由 Java 来调用,这种方式就是本地方法。
回某个对象的散列值:内存地址结合对象内部信息得出的
重写后hashCode
@Override
public int hashCode() {
return this.id;
}
1.3包装类
1.3.1什么是包装类
- 8 种基本数据类型
- 引用类型
通过构造函数 new 出来的对象是引用类型,基本数据类型不是对象。
包装类就是 Java 提供的一组类,专门用来创建 8 种基本数据类型对应的对象。
1.3.2装箱和拆箱
装箱:将基本数据类型转为对应的包装类对象
拆箱:将包装类对象转为对应的基本数据类
装箱(括号是传入的)
1、public Type(type vlaue) 构造器Type方法
public class Test {
public static void main(String[] args) {
byte b = 1;
Byte byt = new Byte(b);
short s = 2;
Short shor = new Short(s);
int i = 3;
Integer integer =