You have seen how to write simple constructors that define the initial state of your objects. However, because object construction is so important, Java offers quite a variety of mechanisms for writing constructors. We go over these mechanisms in the sections that follow.
Recall that the GregorianCalendar class had more than one constructor. We could useor
This capability is called overloading. Overloading occurs if several methods have thesame name (in this case, the GregorianCalendar constructor method) but different parameters. The compiler must sort out which method to call. It picks the correct method bymatching the parameter types in the headers of the various methods with the types ofthe values used in the specific method call. A compile-time error occurs if the compilercannot match the parameters or if more than one match is possible. (This process iscalled overloading resolution.)
NOTE: Java allows you to overload any method—not just constructor methods. Thus, to completely describe a method, you need to specify the name of the method together with its parameter types. This is called the signature of the method. For example, the String class has four public methods called indexOf. They have signatures
The return type is not part of the method signature. That is, you cannot have two methods with the same names and parameter types but different return types.
Default Field Initialization
If you don’t set a field explicitly in a constructor, it is automatically set to a defaultvalue: numbers to 0, boolean values to false, and object references to null. But it is considered poor programming practice to rely on this. Certainly, it makes it harder for some one to understand your code if fields are being initialized invisibly.
NOTE: This is an important difference between fields and local variables. You must always explicitly initialize local variables in a method. But if you don’t initialize a field in a class, it is automatically initialized to a default (0, false, or null).
For example, consider the Employee class. Suppose you don’t specify how to initialize some of the fields in a constructor. By default, the salary field would be initialized with 0and the name and hire Day fields would be initialized with null.
However, that would not be a good idea. If anyone called the getName or get Hire Day method, then they would get a null reference that they probably don’t expect:
A default constructor is a constructor with no parameters. For example, here is a default constructor for the Employee class:
If you write a class with no constructors whats oever, then a default constructor is provided for you. This default constructor sets all the instance fields to their default values.So, all numeric data contained in the instance fields would be 0, all boolean values wouldbe false, and all object variables would be set to null.
If a class supplies at least one constructor but does not supply a default constructor, it isillegal to construct objects without construction parameters. For example, our original Employee (String name, double salary, int y, int m, int d)With that class, it was not legal to construct default employees. That is, the call
CAUTION: Please keep in mind that you get a free default constructor only when your class has no other constructors. If you write your class with even a single constructor of your own and you want the users of your class to have the ability to create an instance by a call tonewClassName()
then you must provide a default constructor (with no parameters). Of course, if you are happy with the default values for all fields, you can simply supply
Explicit Field Initialization
Because you can overload the constructor methods in a class, you can obviously build inmany ways to set the initial state of the instance fields of your classes. It is always agood idea to make sure that, regardless of the constructor call, every instance field is setto something meaningful.
You can simply assign a value to any field in the class definition. For example:
This assignment is carried out before the constructor executes. This syntax is particularly useful if all constructors of a class need to set a particular instance field to the same value.
The initialization value doesn’t have to be a constant value. Here is an example in whicha field is initialized with a method call. Consider an Employee class where each employee has an id field. You can initialize it as follows:
C++ NOTE: In C++, you cannot directly initialize instance fields of a class. All fields must be set in a constructor. However, C++ has a special initializer list syntax, such as
C++ uses this special syntax to call field constructors. In Java, there is no need for it because objects have no subobjects, only pointers to other objects.
When you write very trivial constructors (and you’ll write a lot of them), then it can be some what frustrating to come up with parameter names.
We have generally opted for single -letter parameter names:
However, the drawback is that you need to read the code to tell what the n and sparameters mean.
Some programmers prefix each parameter with an “a”:
That is quite neat. Any reader can immediately figure out the meaning of the parameters.
Another commonly used trick relies on the fact that parameter variables shadow instance fields with the same name. For example, if you call a parameter salary, then salary refers tothe parameter, not the instance field. But you can still access the instance field as this.salary.
Recall that this denotes the implicit parameter, that is, the object that is being constructed.
Here is an example:
C++ NOTE: In C++, it is common to prefix instance fields with an underscore or a fixed letter. (The letters m and x are common choices.) For example, the salary field might be called_salary, mSalary, or xSalary. Java programmers don’t usually do that.
Calling Another Constructor
The keyword this refers to the implicit parameter of a method. However, the keywordhas a second meaning.
If the first statement of a constructor has the form this(. . .), then the constructor calls another constructor of the same class. Here is a typical example:
When you call new Employee(60000), then the Employee (double) constructor calls the Employee(String, double) constructor.
Using thethis keyword in this manner is useful —you only need to write common construction code once.
C++ NOTE: The this reference in Java is identical to the this pointer in C++. However, in C++ it is not possible for one constructor to call another. If you want to factor out common initialization code in C++, you must write a separate method.
You have already seen two ways to initialize a data field:
There is actually a third mechanism in Java; it’s called an initialization block. Class declaration scan contain arbitrary blocks of code. These blocks are executed whenever anobject of that class is constructed. For example:
In this example, the id field is initialized in the object initialization block, no matterwhich constructor is used to construct an object. The initialization block runs first, andthen the body of the constructor is executed.
This mechanism is never necessary and is not common. It usually is more straightforwardto place the initialization code inside a constructor.
NOTE: It is legal to set fields in initialization blocks even though they are only defined later in the class. Some versions of Sun’s Java compiler handled this case incorrectly (bug # 4459133). This bug has been fixed in Java SE 1.4.1. However, to avoid circular definitions, it is not legal to read from fields that are only initialized later. The exact rules are spelled out in section 188.8.131.52 of the Java Language Specification. Because the rules are complex enough to baffle the compiler implementors, we suggest that you place initialization blocks after the field definitions.
With so many ways of initializing data fields, it can be quite confusing to give all possible pathways for the construction process. Here is what happens in detail when a constructoris called:
Naturally, it is always a good idea to organize your initialization code so that another programmer could easily understand it without having to be a language lawyer. Forexample, it would be quite strange and some what error prone to have a class whose constructors depend on the order in which the data fields are declared.
You initialize a static field either by supplying an initial value or by using a static initialization block. You have already seen the first mechanism:
If the static fields of your class require complex initialization code, use a static initialization block.
Place the code inside a block and tag it with the keyword static. Here is an example. We want the employee ID numbers to start at a random integer less than 10,000.
Static initialization occurs when the class is first loaded. Like instance fields, static fieldsare 0, false, or null unless you explicitly set them to another value. All static field initializers and static initialization blocks are executed in the order in which they occur in theclass declaration.
NOTE: Here is a Java trivia fact to amaze your fellow Java coders: You can write a “Hello, World” program in Java without ever writing a main method.
When you invoke the class with java Hello, the class is loaded, the static initialization block prints “Hello, World,” and only then do you get an ugly error message that main is not defined. You can avoid that blemish by calling System.exit(0) at the end of the static initialization block.
The program in Listing below shows many of the features that we discussed in this section:
Object Destruction and the finalize Method
Some object-oriented programming languages, notably C++, have explicit destructor methods for any cleanup code that may be needed when an object is no longer used.The most common activity in a destructor is reclaiming the memory set aside for objects.Because Java does automatic garbage collection, manual memory reclamation is not needed and so Java does not support destructors.
Of course, some objects utilize a resource other than memory, such as a file or a handleto another object that uses system resources. In this case, it is important that the resource be reclaimed and recycled when it is no longer needed.
You can add a finalize method to any class. The finalize method will be called before the garbage collector sweeps away the object. In practice, do not rely on the finalize method forrecycling any resources that are in short supply—you simply cannot know when thismethod will be called.
NOTE: The method call System.runFinalizersOnExit(true) guarantees that finalizer methods are called before Java shuts down. However, this method is inherently unsafe and has been deprecated. An alternative is to add “shutdown hooks” with the method Runtime.addShutdownHook —see the API documentation for details.
If a resource needs to be closed as soon as you have finished using it, you need to manage it manually. Supply a method such as dispose or close that you call to clean up whatneeds cleaning. Just as importantly, if a class you use has such a method, you need tocall it when you are done with the object.
Core Java Related Interview Questions
|J2EE Interview Questions||Core Java Interview Questions|
|JDBC Interview Questions||JSP Interview Questions|
|Android Interview Questions||JavaServer Faces (JSF) Interview Questions|
|Java collections framework Interview Questions||Java 8 Interview Questions|
|Java Collections Interview Questions||Java Exception Handling Interview Questions|
|Java Concurrency Interview Questions||Java Serialization Interview Questions|
|Java Programmer Interview Questions||Java Inheritance Interview Questions|
|Java IO Interview Questions||Object Oriented Programming in PHP Interview Questions|
Core Java Tutorial
An Introduction To Java
The Java Programming Environment
Fundamental Programming Structures In Java
Objects And Classes
Interfaces And Inner Classes
User Interface Components With Swing
Deploying Applications And Applets
Exceptions, Logging, Assertions, And Debugging
All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd
Wisdomjobs.com is one of the best job search sites in India.