object类

xiaoxiao2026-08-30  16

Java常用类 1.Object类 java.lang.Object 类 Object 是类层次结构的根类。每个类都使用 Object 作为超类。所有对象(包括数组)都实现这个类的方法。 常用方法: public native int hashCode(); 返回该对象的哈希码值 public String toString() { return getClass().getName() + "@" + Integer.toHexString(hashCode()); } 返回该对象的字符串表示。建议所有子类都重写此方法。 public boolean equals(Object obj) { return (this == obj); } 返回其他某个对象是否与此对象“相等”。 注意:当此方法被重写时,通常有必要重写 hashCode 方法,以维护 hashCode 方法的常规协定,该协定声明相等对象必须具有相等的哈希码。 String类重写了equals()和hashCode()方法,可以参考 protected void finalize() throws Throwable {} 当垃圾回收器确定不存在对该对象的更多引用时,由对象的垃圾回收器调用此方法。子类重写 finalize 方法,以配置系统资源或执行其他清除。 protected native Object clone() throws CloneNotSupportedException; 创建并返回此对象的一个副本.所有要进行"克隆"的对象所属的类必须实现java.lang.Cloneable接口.下面给出一个实例实现深度拷贝功能: /** * clone()方法的应用 */ package com.java.basic; /** * @author Administrator * */ class Person implements Cloneable { private String name; private int 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; } public Person() { super(); } public Person(String name, int age) { this(); this.name = name; this.age = age; } @Override public String toString() { // TODO Auto-generated method stub return "Name:" + this.name + "\tAge:" + age; } @Override public Object clone() { Person p = null; try { p = (Person) super.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } return p; } } /** * clone()方法的应用 */ package com.java.basic; /** * @author Administrator * */ public class Book implements Cloneable { String bookName; double price; Person author; public Book(String bookName, double price, Person author) { super(); this.bookName = bookName; this.price = price; this.author = author; } @Override public Object clone() { Book book = null; try { book = (Book) super.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } book.author = (Person) this.author.clone(); return book; } @Override public String toString() { // TODO Auto-generated method stub return "bookName:" + bookName + "\t" + "price:" + price + "\t" + author; } } /** * 深度clone()方法的测试 */ package com.java.basic; public class TestDeepCopy { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Book b1 = new Book("Java编程", 30.50, new Person("张三", 34)); Book b2 = (Book) b1.clone(); b2.price = 44.0; b2.author.setAge(45); b2.author.setName("李四"); b2.bookName = "Java开发"; System.out.println(b1); System.out.println(b2); } }
转载请注明原文地址: https://www.6miu.com/read-5052108.html

最新回复(0)