如何在Java中创建对象

105 阅读4分钟

如何在Java中创建对象

Java是一种面向对象的编程语言,在开发桌面、移动和Web应用程序时使用。在Java中,一切都围绕着对象展开。因此,一个Java类可以被看作是一个对象模板。

在Java中,我们可以通过各种方式创建对象。

  • [使用一个新的关键字]
  • [使用类的newInstance ()方法]
  • [使用构造器类的newInstance()方法]
  • [使用对象序列化和反序列化]
  • [使用clone()方法]

使用一个新的关键字

这是在Java中创建一个对象的最常见和最基本的方法。在这个方法中,我们可以调用带参数或不带参数的构造函数。new 关键字允许我们创建一个新的对象。

语法

class_name object_name = new class_name();

例子

在这个例子中,我们将使用new 关键字创建一个对象。

public class Main{ 
    String s = "Hello World"; 

    public static void main(String args[]) { 
    Main a = new Main(); //creating an object
    System.out.println(a.s); //Outputs Hello World
    } 
}

使用类的newInstance()方法

在这个方法中,一个无参数的构造函数被newInstance() 函数调用来创建一个对象。newInstance() 方法被认为是创建对象的一种反射方式,因为它属于java.lang.reflect.Constructor 类。

Class.forName() 是用来动态加载类的

newInstance() 方法使用以下语法。

 public T newInstance() throws InstantiationException,IllegalAcccessException  
  • 如果该方法或类不能被访问,它将返回IllegalAccessException
  • 如果该类代表一个原始数据类型、一个接口、一个抽象、一个数组类,或者该类没有一个无条件的构造函数,它将返回一个InstantiationException

下面的例子有助于我们理解newInstance() 方法。

public class Main
{ 
    String a = "Hello World"; 
    public static void main(String[] args) { 

            try{ 
                Class b = Class.forName("Main"); 
                Main c = (Main) b.newInstance(); 
                System.out.println(c.a); 
            } catch (ClassNotFoundException ex) { 
                    ex.printStackTrace(); 
            } catch (InstantiationException ex){ 
                    ex.printStackTrace(); 
            } catch (IllegalAccessException ex) { 
                    ex.printStackTrace(); 
            } 
    } 
}

使用构造器类的newInstance()方法

这个方法也是使用newInstance() ,该函数由构造函数提供,在创建对象时使用。这一次,构造函数被参数化了。

语法

public T newInstance(Objects...initargs)  

newInstance() 方法会返回以下异常情况。

  • 如果不能访问构造函数,该方法会抛出IllegalAccessException
  • 如果形式参数和实际参数中的数字不同,它将抛出IllegalArgumentException
  • 如果一个异常被构造函数抛出,它会抛出InvocationTargetException
  • 如果激起的初始化失败,它会抛出ExceptionInitializerError

例子

让我们看一个如何使用newInstance ()方法的例子。

import java.lang.reflect.Constructor;  
import java.lang.reflect.Constructor;  
public class Main {  
String str="Hello World";  
    public static void main(String args[]) {  
        try{  
            Constructor<Main> obj =Main.class.getConstructor();  
            Main myObj = obj.newInstance();  
            System.out.println(myObj.str);  
        }catch(Exception ex) {  
            ex.printStackTrace();  
        }  
    }  
}  

使用对象序列化和反序列化

当我们对一个对象进行序列化和反序列化时,会创建一个新的独立对象。为了创建一个对象,这个方法不需要任何构造函数。

我们将使用Java中的Serializable接口来序列化和反序列化新对象。

对象序列化

序列化涉及到将一个对象的状态转换为字节流。我们使用writeObject() 方法来序列化一个对象。

串行化一个对象时的语法

public final void writeObject(Object obj) throws IOException  

对象反序列化

反序列化是在Java中使用字节流来重新创建一个对象的过程。我们将使用readObject() 方法来反序列化一个对象。

反序列化对象时的语法

public final Object readObject() throws IOException  

例子

在这个例子中,我们使用序列化和反序列化的方法来创建一个对象。

import java.io.*;
class Main implements Serializable
{
    public int a;
    public String b;
    public Main(int a, String b)
    {
        this.a = a;
        this.b = b;
    }
}
class Example1 {
    public static void main(String[] args)
    {
        Main obj = new Main(5, "Engineering Education");
        String filename = "OurExample.ser";       //name of the file which should have .ser  
        /*-----------------Serialization----------*/
        try
        {
            FileOutputStream newFile = new FileOutputStream(filename);  //We are saving the object in the file  
            ObjectOutputStream out = new ObjectOutputStream(newFile);
            out.writeObject(obj);            //object being serialized   
            out.close();                   //ObjectOutputStream closed
            newFile.close();                   //File closed  
            System.out.println("We have serialized the Object ");
        }
        catch(IOException ex)
        {
            ex.printStackTrace();
        }
        Main obj1 = null;
        /*-----------------Deserialization--------*/
        try
        {
            FileInputStream newFile = new FileInputStream(filename); // Here, we are reading the object from the file   
            ObjectInputStream is = new ObjectInputStream(newFile);
            obj = (Main)is.readObject();        //object deserialized 
            is.close();                     //ObjectInputStream closed  
            newFile.close();                   //File closed    
            System.out.println("We have deserialized the Object");
            System.out.println("number = " + obj.a);
            System.out.println("string = " + obj.b);
        }
        catch(IOException ex)
        {
            System.out.println("Am an IOException");
        }
        catch(ClassNotFoundException ex)
        {
            System.out.println("Am an ClassNotFoundException");
        }
    }
} 

使用clone()方法

每当clone() 方法被调用时,它就会创建一个新的对象,然后将旧对象中的所有内容复制到它身上。

当我们使用clone() 方法来创建一个对象时,构造函数不会被调用。我们实现Cloneable 类来使用clone() 方法,如下所示。

语法

object.clone()

例子

让我们看看如何使用clone方法创建一个对象的例子。

class Student implements Cloneable{
    int regno;
    String name;

    Student(int regno,String name){
        this.regno=regno;
        this.name=name;
    }

    public Object clone()throws CloneNotSupportedException{
        return super.clone();
    }

    public static void main(String args[]){
        try{
            Student s1=new Student(203,"Geoffrey");

            Student s2=(Student)s1.clone(); //cloning the s1 object 

            System.out.println(s1.regno+" "+s1.name); //prints the name from the original object
            System.out.println(s2.regno+" "+s2.name); //prints the name from the cloned object
        }
        catch(CloneNotSupportedException c){
            // this error is throne when the cloning process fails
        }
    }
}  

结论

在这篇文章中,我们已经看了在Java中创建对象的不同方法。现在我们可以轻松地在Java中创建对象,而无需使用new 关键字方法。