日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > java >内容正文

java

java在创建对象时必须_Java中5种创建对象的方式

發布時間:2024/9/27 java 23 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java在创建对象时必须_Java中5种创建对象的方式 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

以下是一些在Java中創建對象的方法:

1、 使用new關鍵字

使用new關鍵字是創建對象的最基本方法。這是在java中創建對象的最常見方法。幾乎99%的對象都是這樣創建的。通過使用這個方法,我們可以調用我們想要調用的任何構造函數(無參數或參數化構造函數)。

//Java program to illustrate creation of Object//using new keyword

public classNewKeywordExample

{

String name= "GeeksForGeeks";public static voidmain(String[] args)

{//Here we are creating Object of//NewKeywordExample using new keyword

NewKeywordExample obj = newNewKeywordExample();

System.out.println(obj.name);

}

}

輸出:

GeeksForGeeks

2、使用New Instance

如果我們知道類的名稱并且如果它有一個公共的默認構造函數,我們就可以通過Class.forName來創建類的對象。forName實際上在Java中加載類,但不創建任何對象。要創建類的對象,必須使用類的newInstance()方法。

//Java program to illustrate creation of Object//using new Instance

public classNewInstanceExample

{

String name= "GeeksForGeeks";public static voidmain(String[] args)

{try{

Class cls= Class.forName("NewInstanceExample");

NewInstanceExample obj=(NewInstanceExample) cls.newInstance();

System.out.println(obj.name);

}catch(ClassNotFoundException e)

{

e.printStackTrace();

}catch(InstantiationException e)

{

e.printStackTrace();

}catch(IllegalAccessException e)

{

e.printStackTrace();

}

}

}

輸出:

GeeksForGeeks

3、使用clone()方法

每當對任何對象調用clone()方法時,JVM實際上會創建一個新對象,并將前一個對象的所有內容復制到該對象中。使用clone方法創建對象不會調用任何構造函數。

要使用clone()方法,類要實現Cloneable接口并且實現clone()方法。

//Java program to illustrate creation of Object//using clone() method

public class CloneExample implementsCloneable

{

@Overrideprotected Object clone() throwsCloneNotSupportedException

{return super.clone();

}

String name= "GeeksForGeeks";public static voidmain(String[] args)

{

CloneExample obj1= newCloneExample();try{

CloneExample obj2=(CloneExample) obj1.clone();

System.out.println(obj2.name);

}catch(CloneNotSupportedException e)

{

e.printStackTrace();

}

}

}

輸出:

GeeksForGeeks

注:

這里我們創建的是現有對象的克隆,而不是任何新對象。

類需要實現可克隆接口,否則將拋出CloneNotSupportedException.

4、使用反序列化

每當我們序列化并反序列化一個對象時,JVM會創建一個單獨的對象。在反序列化,JVM不使用任何構造函數來創建對象。

要反序列化對象,我們需要在類中實現可序列化接口。

序列化對象:

importjava.io.Serializable;importjava.time.LocalDate;/***@author:crelle

* @className:Person

*@version:1.0.0

* @date:2020/8/15

* @description:XX

**/

public class Person implementsSerializable {private static final Long serialVersionUID = 237898764368L;public enumSex {

MALE, FEMALE

}privateString name;privateLocalDate birthday;privateSex gender;privateString emailAddress;private intage;publicPerson() {}publicPerson(String name) {this.name =name;

}public voidprintPerson() {

System.out.println(toString());

}publicString getName() {returnname;

}public voidsetName(String name) {this.name =name;

}publicLocalDate getBirthday() {returnbirthday;

}public voidsetBirthday(LocalDate birthday) {this.birthday =birthday;

}publicSex getGender() {returngender;

}public voidsetGender(Sex gender) {this.gender =gender;

}publicString getEmailAddress() {returnemailAddress;

}public voidsetEmailAddress(String emailAddress) {this.emailAddress =emailAddress;

}public intgetAge() {returnage;

}public void setAge(intage) {this.age =age;

}

@OverridepublicString toString() {return "Person{" +

"name='" + name + '\'' +

", birthday=" + birthday +

", gender=" + gender +

", emailAddress='" + emailAddress + '\'' +

", age=" + age +

'}';

}

}

/**

* @author:crelle

* @className:DeserializationExample

* @version:1.0.0

* @date:2020/9/18

* @description:XX

**/

// Java program to illustrate Serializing

// an Object.

import crelle.test.java.auxiliary.beans.Person;

import java.io.*;

class SerializationExample

{

public static void main(String[] args)

{

try

{

Person d = new Person("crelle");

FileOutputStream f = new FileOutputStream("person.txt");

ObjectOutputStream oos = new ObjectOutputStream(f);

oos.writeObject(d);

oos.close();

f.close();

}

catch (Exception e)

{

e.printStackTrace();

}

}

}

反序列化對象:

/***@author:crelle

* @className:DeserializationExample

*@version:1.0.0

* @date:2020/9/18

* @description:XX

**/

//Java program to illustrate creation of Object//using Deserialization.

importcrelle.test.java.auxiliary.beans.Person;import java.io.*;public classDeserializationExample

{public static voidmain(String[] args)

{try{

Person person;

FileInputStream f= new FileInputStream("person.txt");

ObjectInputStream oos= newObjectInputStream(f);

person=(Person) oos.readObject();

System.out.println(person.getName());

}catch(Exception e)

{

e.printStackTrace();

}

}

}

輸出:

crelle

5、使用Constructor類的newInstance()方法:

這類似于類的newInstance()方法。java.lang.reflect.Constructor類中有一個newInstance()方法,可用于創建對象。通過使用此newInstance()方法,它也可以調用參數化構造函數和私有構造函數。

//Java program to illustrate creation of Object//using newInstance() method of Constructor class

import java.lang.reflect.*;public classReflectionExample

{privateString name;

ReflectionExample()

{

}public voidsetName(String name)

{this.name =name;

}public static voidmain(String[] args)

{try{

Constructorconstructor= ReflectionExample.class.getDeclaredConstructor();

ReflectionExample r=constructor.newInstance();

r.setName("GeeksForGeeks");

System.out.println(r.name);

}catch(Exception e)

{

e.printStackTrace();

}

}

}

輸出:

GeeksForGeeks

總結

以上是生活随笔為你收集整理的java在创建对象时必须_Java中5种创建对象的方式的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。