如何在java中调用类的数组上的方法



我是一名初学者,正在做一些关于Java OOP的练习,所以这是我的问题。我有一个具有以下属性的Book类:

private Author[] authors;

我需要一个只返回这些作者的名字(name1,name2,..(的方法。Authors类有一个getName()方法:

public String getName() {
return name;
}

我尝试了以下代码,但它不起作用!

//Method in the Book class
public String getAuthorsNames(){
return authors.getName();
}

我需要循环遍历数组还是有其他方法?

private Author[] authors;是对象Author 的数组

你需要添加索引然后获得名称,这里有一个例子:

class Author {
private String name;
public Author(String name) {
this.name = name;
}

public String getName() {
return this.name;
}

在你的课堂上书本:

class Book {
private Author[] authors;
public Book(int authorsSize) {
authors = new Author[authorsSize];
}

public void setAuthor(int index) {
this.authors[index] = new Author("Author Name"):
}
public String getAuthorName(int index) {
return this.authors[index].getName();
}
public String getAllAuthors() {
String all = "";
for (int i = 0; i < authors.length; i++) {
all += authors[i].getName() + ", ";
}

return all;
}
}

添加作者后。。使用getAllAuthors

---更多---代替Author[] authors = new Authors[size];您可以使用ArrayList<Author> authors = new ArrayList<>();然后你可以使用:

authors.add(new Author("Author name1"));
authors.add(new Author("Author name2"));
authors.add(new Author("Author name3"));
authors.add(new Author("Author name4"));
......

最新更新