更新時間:2022-04-15 09:56:03 來源:動力節點 瀏覽1398次
我們可以通過多種方式在java中創建類的對象,因為我們都知道類提供對象的藍圖,您可以從類創建對象。這個概念被低估了,有時被證明是有益的,因為這個概念被許多程序員繞過,有時甚至會詢問面試的洞察力。
在 Java 中有許多不同的方法來創建對象。讓我們稍后列出它們,稍后 在程序的幫助下單獨討論,以說明我們可以在 Java 中創建對象的內部工作。
使用新關鍵字
使用新實例
使用 clone() 方法
使用反序列化
使用構造函數類的 newInstance() 方法
讓我們一一討論它們,并通過附加一個干凈的 java 程序來實現它們。
在java中使用new關鍵字是創建對象的最基本方式。這是在java中創建對象的最常用方法。幾乎 99% 的對象都是以這種方式創建的。通過使用這個方法,我們可以調用我們想要調用的任何構造函數(無參數或參數化構造函數)。
例子
// Java program to Illustrate Creation of Object
// Using new keyword
// Main class
class GFG {
// Declaring and initializing string
// Custom input string
String name = "GeeksForGeeks";
// Main driver method
public static void main(String[] args)
{
// As usual and most generic used we will
// be creating object of class inside main()
// using new keyword
GFG obj = new GFG();
// Print and display the object
System.out.println(obj.name);
}
}
如果我們知道類的名稱并且如果它有一個公共的默認構造函數,我們可以創建一個對象Class.forName。我們可以使用它來創建一個類的對象。Class.forName 實際上加載 Java 中的類,但不創建任何對象。要創建類的對象,您必須使用類的新實例方法。
例子
// Java program to Illustrate Creation of Object
// Using new Instance
// Main class
class GFG {
// Declaring and initializing string
String name = "GeeksForGeeks";
// Main driver method
public static void main(String[] args)
{
// Try block to check for exceptions
try {
Class cls = Class.forName("GFG");
// Creating object of main class
// using instance method
GFG obj = (GFG)cls.newInstance();
// Print and display
System.out.println(obj.name);
}
// Catch block to handle the exceptions
// Catch block 1
// Handling ClassNotFound Exception
catch (ClassNotFoundException e) {
// Display the exception along with line number
// using printStacktrace() method
e.printStackTrace();
}
// Catch block 2
// Handling InstantiationException
catch (InstantiationException e) {
e.printStackTrace();
}
// Catch block 2
// Handling IllegalAccessException
catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
每當對任何對象調用 clone() 時,JVM 實際上都會創建一個新對象并將前一個對象的所有內容復制到其中。使用 clone 方法創建對象不會調用任何構造函數。為了在對象上使用 clone() 方法,我們需要實現Cloneable并在其中定義clone() 方法。
例子
// Java program to Illustrate Creation of Object
// Using clone() method
// Main class
// Implementing Cloneable interface
class GFG implements Cloneable {
// Method 1
@Override
protected Object clone()
throws CloneNotSupportedException
{
// Super() keyword refers to parent class
return super.clone();
}
// Declaring and initializing string
String name = "GeeksForGeeks";
// Method 2
// main driver method
public static void main(String[] args)
{
GFG obj1 = new GFG();
// Try block to check for exceptions
try {
// Using the clome() method
GFG obj2 = (GFG)obj1.clone();
// Print and display the main class object
// as created above
System.out.println(obj2.name);
}
// Catch block to handle the exceptions
catch (CloneNotSupportedException e) {
// Display the exception
// using printStackTrace() method
e.printStackTrace();
}
}
}
每當我們序列化然后反序列化一個對象時,JVM 都會創建一個單獨的對象。在反序列化中,JVM 不使用任何構造函數來創建對象。要反序列化一個對象,我們需要在類中實現 Serializable 接口。
示例 1
// Java Program Illustrate Serializing an Object
// Importing input output classes
import java.io.*;
// Main class
// Implementing the Serializable interface
class GFG implements Serializable {
// Member variables
private String name;
GFG(String name)
{
// This keyword refers to current object itself
this.name = name;
}
// Main driver method
public static void main(String[] args)
{
// Try block to check for exceptions
try {
// Creating object of class in main() method
GFG d = new GFG("GeeksForGeeks");
FileOutputStream f
= new FileOutputStream("file.txt");
ObjectOutputStream oos
= new ObjectOutputStream(f);
oos.writeObject(d);
oos.close();
// Freeing up memory resources
f.close();
}
// Catch block to handle the exceptiona
catch (Exception e) {
// Display the exception along with line number
// using printStacktrace() method
e.printStackTrace();
}
}
}
示例 2
// Java Program Illustrate Creation of Object
// Using Deserialization
// Importing input output classes
import java.io.*;
// Main class
public class GFG {
// Main driver method
public static void main(String[] args)
{
// Try block to check for exceptions
try {
GFG d;
// Creating FileInputStream class object
FileInputStream f
= new FileInputStream("file.txt");
// Creating ObjectInputStream class object
ObjectInputStream oos
= new ObjectInputStream(f);
d = (DeserializationExample)oos.readObject();
}
// Catch block to handle the exceptions
catch (Exception e) {
// Display the exception on console
// using printStacjtrace() method
e.printStackTrace();
}
System.out.println(d.name);
}
}
這類似于類的 newInstance() 方法。java.lang.reflect.Constructor 類中有一個 newInstance() 方法,我們可以使用它來創建對象。它還可以使用這個 newInstance() 方法調用參數化構造函數和私有構造函數。兩種 newInstance() 方法都被稱為創建對象的反射方法。實際上 Class 的 newInstance() 方法內部使用了 Constructor 類的 newInstance() 方法。
例子
// Java program to illustrate creation of Object
// using newInstance() method of Constructor class
// Importing required classes from java.lang package
import java.lang.reflect.*;
// Main class
class GFG {
// Member variables of this class
private String name;
// Constructor of this class
GFG() {}
// Method 1
// To set name ofthe string
public void setName(String name)
{
// This method refers to current object itself
this.name = name;
}
// Main driver method
public static void main(String[] args)
{
// Try block to check fo exceptions
try {
Constructor<GFG> constructor
= GFG.class.getDeclaredConstructor();
GFG r = constructor.newInstance();
// Custom passing
r.setName("GeeksForGeeks");
System.out.println(r.name);
}
// Catch block to handle the exceptions
catch (Exception e) {
// Display the exception on console
// using printStackTrace() method
e.printStackTrace();
}
}
}
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習