Java中创建对象的5种方式

作为

class Employee implements Cloneable, Serializable {     private static final long serialVersionUID = 1L;     private String name;     public Employee() {         System.out.println("Employee Constructor Called...");     }     public String getName() {         return name;     }     public void setName(String name) {         this.name = name;     }     @Override     public int hashCode() {         final int prime = 31;         int result = 1;         result = prime * result + ((name == null) ? 0 : name.hashCode());         return result;     }     @Override     public boolean equals(Object obj) {         if (this == obj)             return true;         if (obj == null)             return false;         if (getClass() != obj.getClass())             return false;         Employee other = (Employee) obj;         if (name == null) {             if (other.name != null)                 return false;         } else if (!name.equals(other.name))             return false;         return true;     }     @Override     public String toString() {         return "Employee [name=" + name + "]";     }     @Override     public Object clone() {         Object obj = null;         try {             obj = super.clone();         } catch (CloneNotSupportedException e) {             e.printStackTrace();         }         return obj;     } }
复制代码

下面的Java程序中,我们将用5种方式创建Employee对象。你可以从GitHub找到这些代码。

复制代码
public class ObjectCreation {     public static void main(String... args) throws Exception {         // By using new keyword        Employee emp1 = new Employee();         emp1.setName("Naresh");         System.out.println(emp1 + ", hashcode : " + emp1.hashCode());         // By using Class class's newInstance() method        Employee emp2 = (Employee) Class.forName("org.programming.mitra.exercises.Employee")                                .newInstance();         //

                    
                
50000+
5万行代码练就真实本领
17年
创办于2008年老牌培训机构
1000+
合作企业
98%
就业率

联系我们

电话咨询

0532-85025005

扫码添加微信