Even if your genre
field was public, when you try to assign it in your current code, you would end up with a NullPointerException
anyway, because just creating an array of objects does not actually create objects inside it. This is where your constructor comes in.
This function:
public Painting (String aGenre) {
genre = aGenre;
}
is called a constructor. What it does is create a new object and, in this case, take the String
called “aGenre” and assign it to the object’s genre
field. You can use this to fill out the array you created with Painting
s with the correct genres.
Painting [] p = new Painting [4];
p[0] = new Painting("Brush");
p[1] = new Painting("Crayon");
p[2] = new Painting("Pencil");
p[3] = new Painting("Watercolour");
The other function you asked about:
public String getGenre(){
return genre;
}
simply returns the genre assigned to the object you call it on. For example:
String str = p[0].getGenre(); // str now has the value "Brush"
str = p[1].getGenre(); // str now has the value "Crayon"
solved Don’t understand lines and how to assign genres to objects in this class