ptg7068951
Creating Behavior with Methods 143
different names, but methods also can have the same name if they have
different arguments.
Two methods can have the same name if they have a different number of
arguments or the arguments are of different variable types. For example, it
might be useful for the Virusclass of objects to have two tauntUser()
methods. One could have no arguments and would deliver a generic taunt.
The other could specify the taunt as a string argument. The following
statements implement these methods:
voidtauntUser() {
System.out.println(“That has gotta hurt!”);
}
voidtauntUser(String taunt) {
System.out.println(taunt);
}
The methods have the same name, but the arguments differ—one has no
argument, the other has a single Stringargument. The arguments to a
method are called the method’ssignature. A class can have different meth-
ods with the same name as long as each method has a different signature.
Constructor Methods
Whenyou want to create an object in a program, the newstatement is used,
as in the following example:
Virus typhoid = new Virus();
This statement creates a new Virusobject called typhoid. When you use
the newstatement, a special method of that object’s class is called. This
method is called a constructorbecause it handles the work required to cre-
ate the object. The purpose of a constructor is to set up any variables and
call the methods that must take place for the object to function properly.
Constructors are defined like other methods, except they cannot return a
value. The following are two constructors for the Virusclassof objects:
publicVirus() {
String author = “Ignoto”;
int maxFileSize = 30000;
}
publicVirus(String name, int size) {
author = name;
maxFileSize = size;
}