是否可以通过Java中的单个类声明创建多个对象?

时间:2019-09-12 11:20:40

标签: 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");

2 个答案:

答案 0 :(得分:0)

您知道“设置信息”从概念上讲就是构造函数的工作,对吧?

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

Providing Constructors for Your Classes

答案 1 :(得分:0)

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

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");

但是,对于您的特定示例,您可能想要检查如何使用构造函数,正如Michael在其回答中指出的那样。我认为这正是您想要的。