In addition to overloading normal methods, you can also overload constructor methods. In fact, for most real-world classes thought create, overloaded constructors will be the norm, not the exception. To undercut stand why, let’s return Lo the Box class’ developed in the preceding chapter. Following is the latest version As you can see, the Box() constructor requires three parameters. This means that all declarations of Box objects must pass three arguments to the Box ) constructor. For example, the following statement’is currently invalid.
Since Box() requires three arguments, it’s an error to call it without them. This raises some important questions. What if wanted a box and did not care (or know) what its initial dimensions were? Or, what if you want to be able to initialize a cube by unsuspectingly one value-that would be used for all three dimensions? As the class is current!y written, these other options are not available to you. . Fortunately, the solution to these problems is quite easy: simply overload the Box constructor so that it handles the situations just described. Here is n program that contains an improved version of Box that does just that.
As you can see, the equals( ) method inside Test compares two objects for equality and returns result. That is, it compares the invoking object with the one that it is passed. If they contain the same values, then the method returns true. Otherwise, it returns.false. Notice that”the parameter 0 in equals( ) specifies Test as its type. Although Test Is a class type created by the program, it is used in just the same way as Java’s built-in types. One of the most common uses of object parameters involves constructors. Frequently you will want to construct a new object so that it is initially the same as some existing object. To do this, you must define a constructor-that takes an object of its class as a parameter. For example, the following version of Box allows one object to initialize another.