[英]How to assign objects created into an array in different class
I am a very new beginner at Java and trying to make an array that holds objects created from another class.我是一个非常新的 Java 初学者,正在尝试创建一个包含从另一个类创建的对象的数组。
To break it down, I have a class called TextBook
, which stores the title of the book, and LibraryClass
, which has a TextBook[] bookShelf
member variable.分解一下,我有一个名为
TextBook
的类,它存储书的标题,还有一个LibraryClass
,它有一个TextBook[] bookShelf
成员变量。 This member array is where the textbooks will be stored.这个成员数组是存储教科书的地方。
So I think what I need to do is:所以我认为我需要做的是:
public class LibraryClass
{
private TextBook[] bookShelf;
public static void main(TextBook[] args, int x) {
TextBook [] bookShelf = new TextBook[x];
for(int i=0;i<bookShelf.length;i++)
{
bookShelf[i] = TextBook[];
}
}
bookShelf[i] = TextBook[];
is where I am stuck.是我被困的地方。 The new textbook objects created will come out like
textBook1
, textBook2
, textBook3
and so on.创建的新教科书对象将像
textBook1
、 textBook2
、 textBook3
等一样textBook1
。 I need to somehow link bookShelf[i]
to textBook1,2,3
etc. but how??我需要以某种方式将
bookShelf[i]
链接到textBook1,2,3
等,但如何?
bookShelf[i] = new TextBook();
instead of bookShelf[i] = TextBook[];
而不是
bookShelf[i] = TextBook[];
assuming your TextBook class had a no args constructor.假设您的 TextBook 类没有 args 构造函数。
This is how you create a new object new
is a necessary keyword for this, and calling TextBook()
will call the constructor of the object.这就是你如何创建一个新对象
new
是一个必要的关键字,调用TextBook()
将调用对象的构造函数。
Every index in the array will have a new TextBook object.数组中的每个索引都有一个新的 TextBook 对象。
These objects can be accessed with bookShelf[i]
where i
is the index of the object you are trying to access.可以使用
bookShelf[i]
访问这些对象,其中i
是您尝试访问的对象的索引。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.