Java Reference
In-Depth Information
public class Book {
String title;
String author;
boolean isRead;
int numberOfReadings;
 
public void read(){
isRead = true;
}
 
public void read(){
numberOfReadings++;
}
}
If you try this first example in Eclipse, you'll see there are errors indicating the read() method is
duplicated. The problem is you have two methods with the same name and neither has any param-
eters. Try the following instead:
public class Book {
String title;
String author;
boolean isRead;
int numberOfReadings;
public void read(){
isRead = true;
numberOfReadings++;
}
public void read(int i){
isRead = true;
numberOfReadings += i;
}
}
Now you have one method with the name read() and no parameters and another method with the
name read() and one int parameter. To Java, these are two completely different methods, so you won't
have any duplication errors. Of course, read(1) will have the same effect as read() , so you might not
see much use for this concept. Alternatively, you could change the name of the methods to readOnce()
and read(int i) . You could easily avoid overloading methods at all in this example.
There is one type of method where overloading becomes very convenient: the constructor. This is
because, as you learned in Chapter 4, the name of constructor methods is restricted to the class
name. So if you want to create more than one constructor, you need to use the overloading principle.
In the Book class, you would naturally want a constructor with two String parameters to set the title
and author of the topic.
public Book(String bookTitle, String authorName){
title = bookTitle;
author = authorName;
}
Search WWH ::




Custom Search