![]() |
Sponsored Link •
|
Advertisement
|
Advertisement
|
This page contains an archived post to the Java Answers Forum made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.
Message:
Wow, I didn't feel like I've learned anything and came across
> Your original attempt failed because in the absence of any other explicitly declared constructor, Java automatically makes a default constructor with no arguments (doesn't do anything, either). So new ATypeName() would work, since that uses this default constructor. The constructor you wanted would have to be specifically written, something like: > public class ATypeName { > // default constructor goes here if wanted (see below) > public ATypeName(String wow) > public String toString() > > Note that this introduces another difficulty: there is now no default constructor! Since a non-default constructor has been supplied, Java does not supply a default constructor by itself, so if you want one (i.e., if you want your original working code not to break) you have to supply one: > public ATypeName() > This is actually more than had to be done: if the contents of the constructor had been empty, the String variable wow would still have been initialized to null, since this is the default behavior of instance variables (variables that belong to a class, but are declared outside a specific method). > But it's clearer this way, particularly since you can see the behavior of "this", which in this case is equivalent to calling the other constructor and passing it null for a parameter. This is perfectly legal, and is in fact the preferred way to arrange multiple constructors, particular in the common situation that you need a lot of information, and want to arrange constructors that take in less than you need but will fill in the deficits with default values. If, for instance, you wanted a default value of "Wow!" for your class, you could do that this way: > public ATypeName() > Now if you give the constructor nothing, it will save "Wow!" to the variable, but if you give it a string, it will save that string. > Hope this helps. > David Sills
> > Chapter 2: Everything is an object - exercise 2 says, "Find the > > I did get it to compile and run with: > > //OutPut was: ATypeName@774a07df > > ...even though this is probally not what Mr. Eckel meant. But I > > //OutPut: ATypeName2.java:4: Wrong number of arguments in constructor. > > Could someone who is familiar with "TIJ" please go through > > Thanks, Steve
Replies: |
Sponsored Links
|