Skip to content

Java Object类

标签:Java
创建时间:2022/10/01 16:55:57

介绍

在 Java 中所有类均继承 Object 类。

clone() 方法

作用

克隆一个对象,返回值是 Object 类型。

用法

若一个类型的对象想实现 clone 方法,需要遵循一下几点:

  1. 类要实现 Cloneable 接口。
  2. 在类中充血 clone 方法。
  3. 使用 clone 方法创建对象(这要要使用异常处理)

代码实现

  1. Student 类

    java
    public class Student 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; }
    
        @Override
        protected Object clone() throws CloneNotSupportedException {
            return super.clone();
        }
    }
  2. Demo 类

    java
    public class Demo01 {
        public static void main(String[] args) {
            Student stu1 = new Student();
            stu1.setName("张三");
            stu1.setAge(20);
    
            try {
                Student stu2 = (Student) stu1.clone();
                System.out.println(stu2.getName());
                System.out.println(stu2.getAge());
            } catch (CloneNotSupportedException e) {
                e.printStackTrace();
            }
        }
    }
  3. 运行结果

equals() 方法

作用

  1. 判断两个对象的内存地址是否一样,同 ==。
  2. 开发过程中可能会被重写,并不是每次都判断对象的内存地址,还有可能是判断对象的数据是否一样。

代码实现

  1. Student 类同上。

  2. Demo 类

    java
    public class Demo01 {
        public static void main(String[] args) {
            Student stu1 = new Student();
            stu1.setName("张三");
            stu1.setAge(20);
    
            try {
                Student stu2 = (Student) stu1.clone();
                Student stu3 = stu2;
                System.out.println(stu2.equals(stu1));
                System.out.println(stu2.equals(stu3));
            } catch (CloneNotSupportedException e) {
                e.printStackTrace();
            }
        }
    }
  3. 运行结果

toString() 方法

作用

  1. 将数据转化为字符串。
  2. 当输出一个对象时,首先找到对象的内存地址,再调用 toString 方法转成字符串后输出。

代码实现

  1. 在 Student 类中重写 toString 方法

    java
    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
  2. Demo 类

    java
    public class Demo01 {
        public static void main(String[] args) {
            Student stu1 = new Student();
            stu1.setName("张三");
            stu1.setAge(20);
    
            try {
                Student stu2 = (Student) stu1.clone();
                System.out.println(new Demo01().toString());
                System.out.println(stu2.toString());
            } catch (CloneNotSupportedException e) {
                e.printStackTrace();
            }
        }
    }
  3. 运行结果

基于 MIT 许可发布