Java Reference
In-Depth Information
You might also need to create a book with an unknown author, perhaps for a publisher who has a
particular book in mind but hasn't hired an author to write it.
public Book(String bookTitle){
title = bookTitle;
author = "Unknown";
}
On the other hand, you might have a book proposal from a known author, but you aren't yet sure
what it will be named.
public Book(String authorName){
title = "Unknown";
author = authorName;
}
Now you have a problem. You have one kind of “method” called Book() , with one String param-
eter for the title, and another method called Book() with one String parameter for the author's
name. Java cannot distinguish between these, so it will be considered a duplicate method. You will
have to remove one of these and use one of the remaining constructors, for example, Book myBook
= new Book("Unknown", "Bart Baesens"); to construct a book with unknown title and known
author using the two String parameter constructor.
You could also add a constructor with no parameters if neither the title nor the author is known. Or
you could add constructors with even more parameters:
public Book(String bookTitle, String authorName, boolean hasBeenRead){
title = bookTitle;
author = authorName;
isRead = hasBeenRead;
}
 
public Book(String bTitle, String aName, boolean hasBeenRead, int read){
title = bTitle;
author = aName;
isRead = hasBeenRead;
numberOfReadings = read;
}
You might already notice quite a bit of repetition in these different constructors. You will see a way
to reduce this in the next section by using the this keyword.
the this KeyWord
This section covers how and why to use the Java this keyword. The this keyword is placed inside
an instance method or constructor in order to refer to the object whose method is being called. This
is perhaps best explained with an example:
public class Person {
String name;
 
public Person(String personName){
 
Search WWH ::




Custom Search