📜  在Java中创建对象的不同方法

📅  最后修改于: 2022-05-13 01:54:32.981000             🧑  作者: Mango

在Java中创建对象的不同方法

我们可以通过多种方式在Java中创建类的对象,因为我们都知道类提供对象的蓝图,您可以从类创建对象。这个概念被低估了,有时被证明是有益的,因为这个概念被许多程序员绕过,有时甚至会询问面试的洞察力。

方法:

在Java中有许多不同的方法来创建对象。让我们列出它们稍后讨论 稍后在程序的帮助下单独展示内部工作,我们可以通过这些工作在Java中创建对象。

  1. 使用新关键字
  2. 使用新实例
  3. 使用 clone() 方法
  4. 使用反序列化
  5. 使用构造函数类的 newInstance() 方法

让我们一一讨论它们,并通过附加一个干净的Java程序来实现它们。

方法一:使用新关键字

在Java中使用new关键字是创建对象的最基本方式。这是在Java中创建对象的最常用方法。几乎 99% 的对象都是以这种方式创建的。通过使用这个方法,我们可以调用我们想要调用的任何构造函数(无参数或参数化构造函数)。

例子

Java
// 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);
    }
}


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();
        }
    }
}


Java
// 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();
        }
    }
}


Java
// 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();
        }
    }
}


Java
// 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);
    }
}


Java
// 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 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();
        }
    }
}


输出
GeeksForGeeks

方法2:使用新实例

如果我们知道类的名称并且如果它有一个公共的默认构造函数,我们可以创建一个对象Class.forName 。我们可以使用它来创建一个类的对象。 Class.forName 实际上加载Java中的类,但不创建任何对象。要创建类的对象,您必须使用类的新实例方法。

例子

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();
        }
    }
}

输出:

GeeksForGeeks

方法 3:使用 clone() 方法

每当对任何对象调用 clone() 时,JVM 实际上都会创建一个新对象并将前一个对象的所有内容复制到其中。使用 clone 方法创建对象不会调用任何构造函数。为了在对象上使用 clone() 方法,我们需要实现 Cloneable 并在其中定义clone() 方法

例子

Java

// 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();
        }
    }
}
输出
GeeksForGeeks

方法四:使用反序列化

每当我们序列化然后反序列化一个对象时,JVM 都会创建一个单独的对象。在反序列化中,JVM 不使用任何构造函数来创建对象。要反序列化一个对象,我们需要在类中实现 Serializable 接口。

示例 1

Java

// 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();
        }
    }
}

输出:

GeeksForGeeks

示例 2

Java

// 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);
    }
}

输出:

GeeksForGeeks

方法五:使用构造函数类的newInstance()方法

这类似于类的 newInstance() 方法。有一个 newInstance() 方法 Java.lang.reflect.Constructor 类,我们可以使用它来创建对象。它还可以使用这个 newInstance() 方法调用参数化构造函数和私有构造函数。两种 newInstance() 方法都被称为创建对象的反射方法。实际上 Class 的 newInstance() 方法内部使用了 Constructor 类的 newInstance() 方法。

例子

Java

// 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 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();
        }
    }
}

输出:

GeeksForGeeks