java中创建对象的方法有多少种?

丘处机 / 2023-08-15 / 原文

第1种:使用new关键字创建。

比如有一个Person类,创建一个person对象就是:

1 Person person = new Person();

 第2种,clone方法。

这种方法必须先实现Cloneable接口并复写Object的clone方法。

 1 public class Student implements Cloneable{
 2     private String name;
 3     private int age;
 4 
 5     public void study(){
 6         System.out.println(this.name+"在学习");
 7     }
 8     @Override
 9     protected Object clone() throws CloneNotSupportedException {
10         return super.clone();
11     }
12 
13     public Student() {
14     }
15     public String getName() {
16         return name;
17     }
18 
19     public void setName(String name) {
20         this.name = name;
21     }
22 
23     public int getAge() {
24         return age;
25     }
26 
27     @Override
28     public String toString() {
29         return "Student{" +
30                 "name='" + name + '\'' +
31                 ", age=" + age +
32                 '}';
33     }
34 
35     public void setAge(int age) {
36         this.age = age;
37     }
38 }
 public static void main(String[] args) throws CloneNotSupportedException {
        Student student1 = new Student();
        student1.setAge(10);
        student1.setName("张三");
        System.out.println("student1 is "+student1.toString());
        Object clone = student1.clone();
        System.out.println("clone student1 is "+clone.toString());

    }