Home > Mobile >  How to call a method on a array of a class in java
How to call a method on a array of a class in java

Time:04-09

I'm a begginer doing some exercises on Java OOP so here's my problem. I have a Book class with this attribute:

private Author[] authors;

I need a method that returns just the names of those authors(name1,name2,..). The class Authors has a getName() method:

public String getName(){
        return name;
}

And I tried this but it doesn't work:

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

Do I need to loop through the array or is there another way?

CodePudding user response:

private Author[] authors; is array of object Author

you need to add the index then get the name, here is an example:

class Author {

  private String name;

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

and in your class Book:

  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;
   }

  }

After adding Authors .. use getAllAuthors

--- more --- Instead of Author[] authors = new Authors[size]; You can use ArrayList<Author> authors = new ArrayList<>(); then you can use:

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