Reputation: 71
I am making a simple program that sets the title and name of an object: book1
. Eventually, the goal is to have several books under the Patron
class that will use the Book
class to assign values. However, I am running into difficulty simply getting the Patron
class to acknowledge the Book
class methods.
Basic Tester/Main method:
import java.util.Scanner;
public class ProjectFiveSix {
public static void main(String[] args) {
String title = "Bob";
String name = "Hugo"; // name of patron (class assigning book)
String author = "Rodrigo";
Patron patronOne = new Patron();
patronOne.setName(name);
Patron Class :
public class Patron {
private String name;
private Book book1;
private Book book2;
private Book book3;
public Patron(){
name = "";
book1 = null;
book2 = null;
book3 = null;
}
public String setName(String name){
return name;
}
public String borrowBook(String book1, String titleFinal, String authorFinal, String title, String author){
if (book1 == null){
book1.setTitle(titleFinal); //**
book1.setAuthor(authorFinal); //***
}
}
}
Book Class:
public class Book {
private String titleFinal;
private String authorFinal;
public Book(){
titleFinal = "";
authorFinal = "";
}
public String setTitle(String title){
titleFinal = title;
return titleFinal;
}
public String setAuthor(String author){
authorFinal = author;
return authorFinal;
}
}
Here I am getting "Cannot find Symbol" on both lines book1.settitle
and book1.setauthor
. The book has been instantiated and I cannot figure out the problem.
Thanks in advance!
Upvotes: 0
Views: 93
Reputation: 178363
You declared your parameter book1
(a String
) as the same name as your instance variable book1
(a Book
). To reference the instance variable, either name the parameter a different variable name, or use this.
to specify the instance variable:
this.book1.setTitle(titleFinal); //**
this.book1.setAuthor(authorFinal); //***
Either way, you'll need to create an actual Book
instance, or else your instance variable book1
will remain null
and you'll get a NullPointerException
.
Upvotes: 1