Sams Teach Yourself Java™ in 24 Hours (Covering Java 7 and Android)

(singke) #1
ptg7068951

144 HOUR 11:Describing What Your Object Is Like


Like other methods, constructors can use the arguments they are sent as a
way to define more than one constructor in a class. In this example, the
first constructor would be called when a newstatement such as the follow-
ing is used:
Virus mumps = new Virus();

The other constructor could be called only if a string and an integer are
sent as arguments with the newstatement, as in this example:
Virus rubella = new Virus(“April Mayhem”, 60000);

If you don’tinclude any constructor methods in a class, it inherits a single
constructor method with no arguments from its superclass. There also
might be other constructor methods that it inherits, depending on the
superclass used.
In any class, there must be a constructor method that has the same number
and type of arguments as the newstatement that’s used to create objects of
that class. In the example of the Virusclass, which has Virus()and
Virus(String name, int size)constructors, you only could create Virus
objects with two different types of newstatements: one without arguments
and one with a string and an integer as the only two arguments.

Class Methods
Likeclass variables, class methods are a way to provide functionality associ-
ated with an entire class instead of a specific object. Use a class method when
the method does nothing that affects an individual object of the class. In the
previous hour, “Creating Your First Object,” you used the parseInt()
method of the Integerclass to convert a string to a variable of the type int:
int fontSize = Integer.parseInt(fontText);

This is a class method. To make a method into a class method, use static
in front of the method name, as in the following code:
static voidshowVirusCount() {
System.out.println(“There are “+ virusCount + “ viruses”);
}

The virusCountclass variable was used earlier to keep track of how many
Virusobjects have been created by a program. The showVirusCount()
methodis a class method that displays this total, and you can call it with a
statement such as the following:
Virus.showVirusCount();
Free download pdf