Diana Diana - 3 months ago 18
Java Question

Get Author-name from Book-class simple

So, I'm new with Object oriented programming. I'm doing the next excercises:


  1. Given a class Book defined as having the following attributes:

    Author author;
    String title;
    int noOfPages;
    boolean fiction;


    write standard
    get
    /
    set
    method headers for each of these attributes.

  2. [Coding] Actually code and compile the Book class based on the attributes and
    get
    /
    set
    methodscalled for in exercise 1.



This is my code:

public class Author {

//private variable
private String name;
private String gender;
//constructor
public Author (String name, String gender){
this.name = name;
this.gender = gender;
}
//getters
public String getName(){
return name;
}
public String getGender(){
return gender;
}
public class Book {

//private variables
private Author author;
private String title;
private int noOfPages;
private boolean fiction;

//constructor
public Book(String title, int noOfPages, boolean fiction){
this.author=new Author ("Jacquie Barker","Female");
this.title = title;
this.noOfPages=noOfPages;
this.fiction = fiction;
}

//getters
public Author getAuthorsName(){
return this.author;
}
public String getTitle(){
return title;
}

public int getNoOfPages(){
return noOfPages;
}

public boolean getFiction(){
return fiction;
}

//setters
public void setAuthor(Author newAuthor){
author=newAuthor;
}
public void setTitle (String title){
this.title=title;
}
public void setNoOfPages(int noOfpages){
this.noOfPages=noOfpages;
}
public void setfiction(boolean fiction){
this.fiction=false;
}

public String toString(){
return "Title: " + this.title + "\n"+"Author: " + this.author + "\n" +
"No. of pages: " + this.noOfPages + "\n" + "Fiction: " + this.fiction;
}
}


Here is the excerpt of main:

Title: Beginning in Java Objects

Author: book.Author@15db9742

No. of pages: 300

Fiction: true


As you can see, the program does not print the name of the author.

I appreciate all help!

Answer

You should be implementing toString in Author class.

    public class Author {

        //private variable
        private String name;
        private String gender;  
        //constructor
        public Author (String name, String gender){
            this.name = name;
            this.gender = gender;   
        }
        ...
        public String toString() {
          return "Name " + name + "\t Gender: " + gender + "\n"; //Somethign like this.
        } 
}