首页 > 解决方案 > 是否可以从 Java 中的单个类声明创建多个对象?

问题描述

我不是java方面的专家。因此,当我在练习课堂时,我认为如果有这样的机会来创建多个对象,那就太好了。有可能吗?或 Ecah 时间我必须声明新对象

  Student s2 = new Sudent();
  Student s1 = new Student();

  s1.setInfo("Sujon", 24, 40000, "Software Engineer");
  s2.setInfo("Alam", 25, 35000, "designer");
  s3.setInfo("Fahim", 23, 20000, "Software Engineer");

标签: java

解决方案


您可以在同一行声明多个变量。但是,在同一行中声明不超过三个变量通常是一个好主意。然后每个变量都需要它自己的实例化,它可以是三个相同类型的不同对象,也可以是同一个对象。这是一个例子:

Student s1, s2, s3;

// Each variable is instantiated to the same object
s1 = new Student ();
s2 = s1;
s3 = s1;

// Each variable is instantiated to a new object
s1 = new Student ();
s2 = new Student ();
s3 = new Student ();

// Now you can make calls to the objects
s1.setInfo("Sujon", 24, 40000, "Software Engineer");
s2.setInfo("Alam", 25, 35000, "designer");
s3.setInfo("Fahim", 23, 20000, "Software");

但是,对于您的特定示例,您可能想查看如何使用构造函数,正如迈克尔在他的回答中指出的那样。我认为这正是您正在寻找的。


推荐阅读