起航学习网

- 让每个人都能学到最前沿新知识、新技能!
起航学习网
当前位置: 起航学习网 > 短期培训 > 编程语言 > 5种Java创建对象的方法

5种Java创建对象的方法

时间:2022-06-08 14:16:37来源:IT培训网 作者:Java学习网 已有: 名学员访问该课程

  快捷搜索:java创建对象的方法

前言: 我们可以通过多种方式在java中创建类的对象,因为我们都知道类提供对象的蓝图,您可以从类创建对象。这个概念被

我们可以通过多种方式在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);
	}
}

方法2:使用新实例

如果我们知道类的名称并且如果它有一个公共的默认构造函数,我们可以创建一个对象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();
		}
	}
}

方法 3: 使用 clone() 方法

每当对任何对象调用 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()方法

这类似于类的 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();
		}
	}
}

 

文章出自:http://qh.itpxw.cn/peixun/software/2022121545.html

文章标题:5种Java创建对象的方法



免责声明:本站文章均由入驻起航学习网的会员所发或者网络转载,所述观点仅代表作者本人,不代表起航学习网立场。如有侵权或者其他问题,请联系举报,必删。侵权投诉

你也许会喜欢如下的文章?
(责任编辑:深圳学历教育网)
顶一下
(0)
0%
踩一下
(0)
0%
------分隔线----------------------------
培训学校
IT培训网 访问该机构站点 报名留言 加为好友 用户等级:注册会员 用户级别:10 机构名称:IT培训网 联 系 人:罗老师 联系电话:13783581536 联系手机:13783581536 在线客服:起航学习网客服 在 线 QQ:起航学习网客服 电子邮件: 网站域名:http://www.itpxw.cn 注册时间:2016-07-18 11:07 最后登录:2024-02-20 13:02
推荐内容