I likeThatMeow
I likeThatMeow

Reputation: 198

How to write a 'get/set method' for an array of type class?

I'm having trouble in the implementation of a get/set method for an array autores[] of type Autor which is another class from the same package. It doesn't work in the same way as the other variables of the class :(

class Autor
{
private String nombre;
private String adscripcion;

Autor(String nombre,String adscripcion)
{
    this.nombre=nombre;
    this.adscripcion=adscripcion;
}
Autor(){}

String getNombre()
{
    return nombre;
}
String getAdscripcion()
{
    return adscripcion;
}

void setNombre(String nombre)
{
    this.nombre=nombre;
}

void setAdscripcion(String adscripcion)
{
    this.adscripcion=adscripcion;
}

} public class Articulo {

private String nombreArt;
private Autor autores[]=new Autor[2];
private String fechaPublicacion;

Articulo(String nombreArt,String fechaPublicacion, String nombre,String adscripcion)
{
    this.nombreArt=nombreArt;
    this.fechaPublicacion=fechaPublicacion;
    autores[0]=new Autor(nombre,adscripcion);
    autores[1]=new Autor(nombre,adscripcion);

}


String getnombreArt()
{
    return nombreArt;
}
String getfechaPublicacion()
{
    return fechaPublicacion;
}
Autor getautores()
{
    return autores[];//this part of the code it's not correct.
}


}

Upvotes: 0

Views: 2500

Answers (3)

Chathura Buddhika
Chathura Buddhika

Reputation: 2195

This part doesn't make any sense;

return autores[];

autores is a variable name and it's an array of Autor objects. So your getter should be something like that,

public Autor[] getAutores() {
    return autores;
}

In here, Autor[] is return type and it will return value of autores variable.

Upvotes: 1

Scary Wombat
Scary Wombat

Reputation: 44834

The getter should look like

public Autor[] getAutores()
{
    return autores;
}

and the setter is like

public void setAutores(Autor[] autores) {
    this.autores = autores;
}

If you use an IDE like Eclipse, then are menu options to generate setter/getter and heaps of other things

Upvotes: 2

Elliott Frisch
Elliott Frisch

Reputation: 201439

First, autores can be declared with your current syntax - but it's a hold-over to make Java more familiar to C and C++ developers. I personally find it easier to read with the type fully on the left of the variable name. Like,

private Autor[] autores = new Autor[2];

For getters and setters of array types, the [] must be written as part of the type. Like,

public Autor[] getAutores() {
    return autores;
}

public void setAutores(Autor[] autores) {
    this.autores = autores;
}

Upvotes: 1

Related Questions