🛸~~ 🚁🚁🚁🛩️🛩️🛩️~|

n1ce2cv

园龄:5年2个月粉丝:4关注:1

类和对象

类和对象

  • 直接通过匿名对象调用方法
// 匿名对象意味着没有引用变量,它只能在创建的时候被使用一次
new Person().initialize("沉默王二", 18, 1);

Object类

对象比较

public native int hashCode()

public native int hashCode();
  • native方法,用于返回对象的哈希码
  • 相等的对象必须具有相等的哈希码。如果重写了 equals 方法,就应该重写 hashCode 方法

public boolean equals(Object obj)

public boolean equals(Object obj) {
return (this == obj);
}
  • 比较 2 个对象的内存地址是否相等
  • 如果比较的是两个对象的值是否相等,就要重写该方法
class Person {
private String name;
private Integer age;
// 省略get set
@Override
public boolean equals(Object o) {
// 哈希码一致返回true
if (this == o) return true;
// o为空或者不是同一个类返回false
if (o == null || getClass() != o.getClass()) return false;
// 强制类型转换后,判断各个属性的值是否一致
Person person = (Person) o;
return Objects.equals(name, person.name) && Objects.equals(age, person.age);
}
// 重写了equals方法,就应该重写hashCode方法
@Override
public int hashCode() {
return Objects.hash(name, age);
}
}

对象拷贝

protected native Object clone() throws CloneNotSupportedException;

protected native Object clone() throws CloneNotSupportedException;
  • naitive 方法,返回此对象的一个副本。默认实现只做浅拷贝,且类必须实现 Cloneable 接口。

对象转字符串

public String toString()

public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
  • 默认实现返回类名@哈希码的十六进制表示,通常重写返回有含义的字符串。
  • 数组也是一个对象

多线程调度

public final void wait() throws InterruptedException

  • 调用该方法会导致当前线程等待,直到另一个线程调用此对象的notify()方法或notifyAll()方法。

public final native void notify()

  • 唤醒在此对象监视器上等待的单个线程。如果有多个线程等待,选择一个线程被唤醒。

public final native void notifyAll()

  • 唤醒在此对象监视器上等待的所有线程。

public final native void wait(long timeout) throws InterruptedException

  • 等待 timeout 毫秒,如果在 timeout 毫秒内没有被唤醒,会自动唤醒。

public final void wait(long timeout, int nanos) throws InterruptedException

  • 更加精确了,等待 timeout 毫秒和 nanos 纳秒,如果在 timeout 毫秒和 nanos 纳秒内没有被唤醒,会自动唤醒。
public static void main(String[] args) {
// 每个对象都可以调用Object的wait/notify方法来实现等待/通知机制
Object o = new Object();
new Thread(() -> {
synchronized (o) {
try {
System.out.println("线程1开始等待");
o.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("线程1被唤醒");
}
}).start();
new Thread(() -> {
synchronized (o) {
System.out.println("线程2唤醒线程1开始");
o.notify();
System.out.println("线程2唤醒线程1结束");
}
}).start();
}

反射

public static void main(String[] args) {
Person person = new Person();
Class<? extends Person> aClass = person.getClass();
// test.Object.Person
System.out.println(aClass.getName());
}

垃圾回收

protected void finalize() throws Throwable

  • 当垃圾回收器决定回收对象占用的内存时调用此方法。用于清理资源,但 Java 不推荐使用,因为它不可预测且容易导致问题,Java 9 开始已被弃用。

本文作者:n1ce2cv

本文链接:https://www.cnblogs.com/sprinining/p/18300991

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   n1ce2cv  阅读(6)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起