Question

Java is telling me that my setter function does not exist... why? When I set the author later in my code I got the error message but my setter for Titles which is basically in the same format returns no error.

class Author {
    String first_name;
    String last_name;
    int birth_year;
    int death_year;
    Author writer;

    Author () {}

    Author(String LastName, String FirstName) {
        first_name= FirstName;
        last_name = LastName;
    }

    Author getAuthor() {
        return writer;
    }
    void setAuthor(Author Writer) {
        Writer = writer;
    }
}
Was it helpful?

Solution

Well, I'm pretty sure that Java isn't telling that. You should always paste the exact error message.

That said, your setter initializes the argument of the setter with the value of the field, instead of initializing the field with the value of the argument.

It should be:

void setAuthor (Author Writer) {
    this.writer = Writer;
}

You should respect the Java naming conventions, and be consistent in your naming. Variables start with a lowercase letter. They naver contain an underscore and are camelCased: firstName, lastName, etc. And using this.xxx = xxx in a systematic way in setters allow avoiding those kinds of bug.

It also seems like you have a design problem. Why would an author have an author? A book should have an author. But an author shouldn't have an author.

OTHER TIPS

  void setAuthor (Author Writer) {
    Writer = writer;
  }

This doesn't set the writer field to the value of the Writer argument. This sets the Writer argument to the value of the writer field. As it stands, it's useless. You want

  void setAuthor (Author Writer) {
    writer = Writer;
  }
void setAuthor (Author Writer) {
    Writer = writer;
  }

Writer = writer; sets the value in the LOCAL variable Writer FROM instance variable writer

make them public like that

public class Author {
      String first_name;
      String last_name;
      int birth_year;
      int death_year;
      Author writer;
      Author () {
      }
      Author(String LastName, String FirstName) {
        first_name= FirstName;
        last_name = LastName;
      }
      public Author getAuthor() {
        return this.writer;
      }
      public void setAuthor (Author Writer) {
        this.writer = Writer;
      }
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top