Jau Lee Jau Lee - 3 months ago 13
Java Question

Don't understand lines and how to assign genres to objects in this class

This is the class Painting:

public class Painting {
private String genre;
public Painting(){
}

public Painting (String aGenre) {
genre = aGenre;
}

public String getGenre(){
return genre;
}
}


From this class I was trying to create 4 objects and assign each a genre which I did below.

public class PaintingGenre {
public static void main(String[] args) {
Painting [] p = new Painting [4];

p[0].genre = "Brush";

p[1].genre = "Crayon";

p[2].genre = "Pencil";

p[3].genre = "Watercolour";


}
}


However, genre is private in the java class.. is there a way to assign these genres to the four objects/ paintings without changing the genre from private to public in the java class?

I think I can somehow do that by using these lines in the java class below but I don't know what it means... could you explain these lines for me and tell me if and how I can assign genres to the paintings using these lines?

public Painting (String aGenre) {
genre = aGenre;
}
public String getGenre(){
return genre;


Thanks very much!

Answer

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 Paintings 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"