Add multiple indices of a vector as parameter

Asked

Viewed 76 times

1

I’m starting in JAVA. I created two classes, the class Pessoa, which receives the following parameters at the instantiation of a new object:

public Pessoa(String nome, int idade, char sexo)

And the class Livro:

public Livro(String titulo, String autor, int totPaginas, Pessoa leitor)

And in the main class, I made the following instantiations:

Pessoa[] p = new Pessoa[2];
Livro [] l = new Livro[3];

p[0] = new Pessoa("Pedro" , 22 , 'M');
p[1] = new Pessoa("Maria" , 25 , 'F');

l[0] = new Livro("Aprendendo JAVA" , "José da Silva"    , 400 , p[0]);
l[1] = new Livro("POO em JAVA"     , "Márcio Bezerra"   , 500 , p[1]);
l[2] = new Livro("JAVA avançado"   , "Fernanda Pereira" , 900 , p[0]);

How to add multiple vector indices Pessoa [] as a parameter in the instantiation of a new book object, i.e., how to do, for example, Peter And Maria read the book "POO in JAVA", without having to instantiate another identical book?

  • I believe that logic is envied. For me it makes no sense to add "Person" in Book just to mark that she has already read it. Maybe the reverse makes it much more sentid and less work.

  • @diegofm you’re right, but the problem of AP will remain, when a person reads more than one book.

  • @ramaral does not stop the Book from being a parameter of the existence of a person object and create a list (in a rudimentary example possible) in the class person where the books read would be stored.

  • @diegofm What I meant was that changing logic did not solve the problem, it needed something more and yes the solution is this: create a list that, although not so "logical", can also be made in the object Book.

1 answer

2

The relationship needs to be Um para Muitos

To have this relationship you need that class Livro has, internally, a List of Pessoa. To do this you can create a method in Livro with the name adicionarPessoa, for example, and after that instantiate the object Livro, can add people.

l[0] = new Livro("Aprendendo JAVA" , "José da Silva"    , 400);
l[0].adicionarPessoa(p[0]);
l[0].adicionarPessoa(p[1]);

l[1] = new Livro("POO em JAVA"     , "Márcio Bezerra"   , 500);
l[1].adicionarPessoa(p[0]);

There’s a question about Composition and Aggregation here at Sopt who can help you understand these relationships.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.