Mohammad Abu Khdair
Mohammad Abu Khdair

Reputation: 35

Printing the name of an object in Java

I have researched, and although this is a really simple issue, I am not sure how to solve it.

The code I have looks like this:

public class Playlist {

   public Playlist(String name) {

   }
}

Separate files of course:

@Test
public void CreatePlaylist(){
    Playlist myPlaylist = new Playlist("Workout Playlist");

}

I am trying to print the actual name of this new playlist "workout playlist" but I can't seem to find a way to do so.

Upvotes: 2

Views: 5478

Answers (4)

Srujan Kumar Gulla
Srujan Kumar Gulla

Reputation: 5851

write get method to name or override toString method in the class

public class Playlist {

   private String name;
    public Playlist (String name) {
        this.name = name;
    }

    public String getName() {
    return name;
}

    @Override
    public String toString() {
        return "Playlist [name=" + name + "]";
    }
}

Print the name using

System.out.println(playlistObject.getName());
or

System.out.println(playlistObject).

I would prefer setting a getter method over toString() though.

Upvotes: 2

Vikram
Vikram

Reputation: 334

You are not at all storing the 'name' property in your object. So obviously you can't access name. One way is

public class Playlist {

    public String name;

    public Playlist(String name) {
       this.name = name;
   }
}

Now you should be able to access your attribute from your testcase like this.

@Test
public void CreatePlaylist(){
    Playlist myPlaylist = new Playlist("Workout Playlist");
    System.out.println(myPlaylist.name);
}

Upvotes: 0

Brian Kerr
Brian Kerr

Reputation: 401

public class Playlist {
  private String name;

  public Playlist(String name) {
     this.name = name;
  }

  public String getName() {
     return name;
  }
}

Then to show the name:

@Test
public void CreatePlaylist(){
    Playlist myPlaylist = new Playlist("Workout Playlist");
    System.out.println(myPlaylist.getName());
}

Upvotes: 0

Ted Hopp
Ted Hopp

Reputation: 234857

You need to store the name of your playlist in an instance variable. For instance:

public class Playlist {
   private final String name;

   public Playlist(String name) {
       this.name = name;
   }

   public String getName() {
       return name;
   }
}

Then you can print it with:

System.out.println(myPlayList.getName());

If you want to make the name mutable, then get rid of the final modifier and add a setName(String) method.

Upvotes: 7

Related Questions