用Java创建对象的不同方法?
在Java中,类是用户定义的数据类型/蓝图,我们在其中声明方法和变量。
public class Sample{
}声明一个类后,您需要创建一个对象(实例化)。您可以使用多种方式创建对象-
使用新关键字
通常,使用new关键字创建对象-
Sample obj = new Sample();
示例
在下面的Java中,我们有一个名称为sample的类,该类具有一个方法(显示)。从main方法开始,我们实例化Sample类并调用该display()方法。
public class Sample{
public void display() {
System.out.println("This is the display method of the Sample class");
}
public static void main(String[] args){
//实例化Sample类
Sample obj = new Sample();
obj.display();
}
}输出结果
This is the display method of the Sample class
使用newInstance()方法
名为Class的类的newInstance()方法创建此Class对象表示的类的对象。
您可以通过将其名称作为String传递给方法来获得类的Class对象forName()。
Sample obj2 = (Sample) Class.forName("Sample").newInstance();示例
在下面的Java中,我们有一个名称为sample的类,该类具有一个方法(显示)。从main方法开始,我们使用Class类的newInstance()方法创建Sample类的对象。
public class Sample{
public void display() {
System.out.println("This is the display method of the Sample class");
}
public static void main(String[] args) throws Exception{
//创建Sample类的Class对象
Class cls = Class.forName("Sample");
Sample obj = (Sample) cls.newInstance();
obj.display();
}
}输出结果
This is the display method of the Sample class
使用clone()方法
Object类的clone()创建并返回当前类的对象。
示例
在下面的Java中,我们有一个名称为sample的类,该类具有一个方法(显示)。从main方法中,我们正在创建Sample类的对象,然后使用clone()方法从中创建另一个对象。
public class Sample{
public void display() {
System.out.println("This is the display method of the Sample class");
}
public static void main(String[] args) throws Exception{
//创建Sample类的Class对象
Sample obj1 = new Sample();
//Creating another object using the clone() method
Sample obj2 = (Sample) obj1.clone();
obj2.display();
}
}输出结果
This is the display method of the Sample class
使用lang.reflect中的构造函数类
java.lang.reflect.Constructor类的newInstance()方法使用当前构造函数创建并返回一个新对象。
示例
在下面的Java中,我们有一个名称为sample的类,该类具有一个方法(显示)。从主要方法中,我们使用java.lang.reflect.Constructor类创建Sample类的对象。
import java.lang.reflect.Constructor;
public class Sample {
public void display() {
System.out.println("This is the display method of the Sample class");
}
public static void main(String[] args) throws Exception{
//创建一个构造器类
Constructor constructor = Sample.class.getDeclaredConstructor();
//Creating an object using the newInstance() method
Sample obj = constructor.newInstance();
obj.display();
}
}输出结果
This is the display method of the Sample class
热门推荐
10 新年门口花束祝福语简短
11 盘锦结婚祝福语大全简短
12 父母生日祝福语 简短独特
13 家庭恩爱祝福语简短英文
14 高考俄语祝福语大全简短
15 虎年祝福语 诗句唯美简短
16 生日婚礼祝福语简短精辟
17 虎年喝酒拜年祝福语简短
18 教师闺蜜祝福语简短