I'm doing some excersises i found online, trying to understand OOP and such, my problem is as it follows, i have 2 classes, mainly a class called Book and one Called Author.
Author posseses 3 attributes: string name, string email and char gender. Book posses 4: String bookname Author[] authors double price int qty
My question is, since i didn't and don't understand what is Author[] supposed to mean, is an Array of objects that stores multiple book authors? if it's that, how should i proceed with it on the main class, should i create an instance of the object Author[] and with a for loop start giving him values? how are the values(name,email,gender) of that object stored in author1[] for example and how should i load values to that object array?
Trying to learn java by myself.
public class Book {
protected static final int QTY_DEF = 0;
private String name;
private Author[] authors;
private double price;
private int qty;
public Book(String name, Author[] authors, double price, int qty) {
this.name = name;
this.authors = authors;
this.price = price;
this.qty = qty;
}
}
public class Author {
private String name;
private String email;
private char gender;
public Author(String name, String email, char gender) {
this.name = name;
this.email = email;
this.gender = gender;
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String name;
String authorname;
String email;
int price;
int qty;
char gender;
Author[] author1 = new Author[3];
System.out.println("Author's name: ");
System.out.println("Author's email: ");
email = sc.nextLine();
System.out.println("Author's gender: ");
gender = sc.next().charAt(0);
Author[] represents and array of the Class Author. So in this property on your Book class you would have an array containing Authors with their own name, email and gender.
Now in the Main class there is an array created of Authors with a size of 3. So you can realistically put 3 Authors in that array until it is full and would need to be expanded.
To do that you can do that with a For loop or directly insert them to their positions on the array:
//Set a new Author per position directly
authors[0] = new Author("Jeff Smith", "[email protected]", "M".toCharArray()[0]);
authors[1] = new Author("Jane Doe", "[email protected]", "F".toCharArray()[0]);
authors[2] = new Author("Brian Smith ", "[email protected]", "M".toCharArray()[0]);
Or with a For Loop where you set the name, email and gender to new values each time through the loop.
String name;
String email;
char gender;
for (int i = 0; i < authors.length; i++) {
authors[i] = new Author(name, email, gender);
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments