java - 是否可以从 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");
解决方案
您可以在同一行声明多个变量。但是,在同一行中声明不超过三个变量通常是一个好主意。然后每个变量都需要它自己的实例化,它可以是三个相同类型的不同对象,也可以是同一个对象。这是一个例子:
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");
但是,对于您的特定示例,您可能想查看如何使用构造函数,正如迈克尔在他的回答中指出的那样。我认为这正是您正在寻找的。
推荐阅读
- javascript - 不确定如何使用 express-zip 将多个文件下载为 zip 文件
- html - 无法为 Angular Material 中的下拉菜单设置默认值
- python - 使用服务帐户返回密钥错误的 Google API
- c++ - 一个 ”?” 在字符串之前
- azure-functions - Azure 函数 - 获取单例锁的速度很慢,为什么需要它?
- python - 循环遍历元素并将它们用作python中对象的名称
- python-3.x - 无法导入本地模块?PyCharm
- enums - 在 Rails 5.2 上是否有调用枚举的新方法?
- javascript - 我是 javascript 新手,我该如何解决这个问题?
- python - 构建失败:如何使用 Pyenv 在 macOS Big Sur 版本 11.0.1 上安装 Python 3.8.3?