Showing posts with label Constructor. Show all posts
Showing posts with label Constructor. Show all posts

Monday, June 27, 2011

JDK7 : Improved type inference for generic instance creation(diamond)

Note the constructor inference which is new to Java 7 also.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class GenericDiamondTypeInference {

    static class MyClass <X> {
        <Y> MyClass(Y y) {
        }
    }

    public static void main(String[] args) {

        // constructor inference
        // <X> = <Integer>, <Y> = <String>
        MyClass<Integer> myClass1 = new MyClass<>("");

        // standard stuff
        List<String> list = new ArrayList<>();
        Map<String, List<String>> map = new HashMap<>();

    }

}

Sunday, June 12, 2011

Insufficient memory problem with StringBuffer

Using string buffer without selecting the proper construction can lead to memory leak.

Lets have a look of the constructor of string buffer

Constructs a string buffer with no characters in it and an initial capacity of 16 characters.
public StringBuffer() {
  super(16);
}


Suppose you are creating objects of type StringBuffer in a loop, no of objects may change depnding upon the input. Every time it will create object to store at least 16 characters, you may not need all the 16, in that case remaining space will be unused and cannout be allocated for other purpose.

At some point these unused memory location may lead to Out of memory problem.

Instead of that we can use another constructor

Constructs a string buffer with no characters in it and the specified initial capacity.
public StringBuffer(int capacity) {
  super(capacity);
}

Thursday, June 9, 2011

Don't use Evil Boolean Constructors

This is something straight out of the Effective Java book, which every, really, every Java developer should read. But I still find a lot of calls to Boolean constructors, to this very day, 6 years after the book was out. (Has doing code review turned me into a grumpy nagging old man or what?)
The twin constructors of java.lang.Boolean, namely, Boolean(String) and Boolean(boolean) should never be called from within your application. The only legit user of these two constructors is the Boolean class itself. The reason is simple: you only need two Boolean instances, really. One to represent true, one to represent false. That’s it. And these two objects already exist as class variables of Boolean, namely, Boolean.TRUE, and Boolean.FALSE. You only need these two.
You don’t need the constructors for converting from the primitive boolean and String either. There are two static methods available just for this purpose. Boolean.valueOf(String) and Boolean.valueOf(boolean). Instead of saying:
Boolean isMad = new Boolean(true);
Boolean isNotCrazy = new Boolean("TRUE");

say -
Boolean isMad = Boolean.valueOf(true);
Boolean isNotCrazy = Boolean.valueOf("TRUE");

Because valueOf() returns either Boolean.TRUE or Boolean.FALSE, instead of creating another unnecessary Boolean instance. For the case when you already know whether to pass true or false, instead of saying:
book.setRegurgitable(new Boolean(false));

simply say
book.setRegurgitable(Boolean.FALSE);

So, be very suspicious of the existence of “new Boolean” in your codebase. If your code is based on JDK 1.4 or above, really, there shouldn’t be any “new Boolean” anymore, anywhere. In fact, if there’s a legit case when one just have to use the Boolean constructors in their code, please let me know, I’ll be grateful.

Monday, May 16, 2011

Object destruction and the finalize method

The aim of destructor in any OOPs language is:

  1. Free up the memory (c++ suffer from memory allocation / deallocation)
  2. Clean up any other resources (like closing of open file stream)

Java take cares of all and hence there is no destructor in JAVA. (With the help of Garbage collection) but still if you want to perform some additional tasks, then you can use the finalize() method of java.

But, we can’t rely on finalize() as it depends on GC. Sometimes, GC may never be invoked during the lifetime of the program. A good idea is to implement a method, say cleanUp() which does, any special processing required, ofcourse, other than freeing up memory. The programmer should call this method at the approppriate place in the program. That is the only way to make sure your program works correctly.

Example code of finalize in java:

class HasFinalize{

public static int number_of_things = 0;
public String what;

public HasFinalize(String what) {
this.what = what;
number_of_things++;
}

protected void finalize () {
number_of_things--;
}
}

public class TestFinalize {
public static void main(String[] args)
{
Thing obj = new Thing("Test App");

}
}


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 what needs cleaning. Just as importantly, if a class you use has such a method, you need to call it when you are done with the object.

Order of initialization in java

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 constructor is called.
  1. All data fields are initialized to their default value (0, false, or null).
  2. All field initializers and initialization blocks are executed, in the order in which they occur in the class declaration.
  3. If the first line of the constructor calls a second constructor, then the body of the second constructor is executed.
  4. The body of the constructor is executed.
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. For example, it would be quite strange and somewhat error prone to have a class whose constructors depend on the order in which the data fields are declared.

Initialization Blocks in java

You have already seen two ways to initialize a data field:
  • By setting a value in a constructor
  • By assigning a value in the declaration
There is actually a third mechanism in Java; it's called an initialization block. Class declarations can contain arbitrary blocks of code. These blocks are executed whenever an object of that class is constructed. For example,

class Employee

{

public Employee(String n, double s)

{

name = n;

salary = s;

}

public Employee()

{

name = "";

salary = 0;

}

. . .

private static int nextId;


private int id;

private String name;

private double salary;

. . .

// object initialization block

{

id = nextId;

nextId++;

}

}



In this example, the id field is initialized in the object initialization block, no matter which constructor is used to construct an object. The initialization block runs first, and then the body of the constructor is executed.

This mechanism is never necessary and is not common. It usually is more straightforward to place the initialization code inside a constructor.


 

Parameter names in constructor in java

When you write very trivial constructors (and you'll write a lot of them), then it can be somewhat frustrating to come up with parameter names.
 
We have generally opted for single-letter parameter names:

public Employee(String n, double s)

{

name = n;

salary = s;

}


However, the drawback is that you need to read the code to tell what the n and s parameters mean.

Some programmers prefix each parameter with an "a":

public Employee(String aName, double aSalary)

{

name = aName;

salary = aSalary;

}



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 to the 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:

public Employee(String name, double salary)

{

this.name = name;

this.salary = salary;

}



 


C++ convention


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.

Cpp vs Java in case of direct field initialization

In java, one can directly initialize instance fields of a class. See here for this.

But 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 sytax such as:

Employee::Employee(String n, double s, int y, int m, int d) // C++

: name(n),

salary(s),

hireDay(y, m, d)

{
//some other logic if needed
}

C++ uses this special syntax to call field constructors. In Java, there is no need for it because objects have no sub-objects, only pointers to other objects.

Explicit or direct Field Initialization in java

Because you can overload the constructor methods in a class, you can obviously build in many ways to set the initial state of the instance fields of your classes. It is always a good idea to make sure that, regardless of the constructor call, every instance field is set to something meaningful.
You can simply assign a value to any field in the class definition. For example,
class Employee

{

. . .

private String name = "";

}



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 which a field is initialized with a method call. Consider an Employee class where each employee has an id field. You can initialize it as follows:

class Employee

{

. . .

static int assignId()

{

int r = nextId;

nextId++;

return r;

}

. . .

private int id = assignId();

}



See cpp vs java in case of direct field initialization.

Default Field Initialization in java

If you don't set a field explicitly in a constructor, it is automatically set to a default value: numbers to 0, Booleans to false, and object references to null. But it is considered poor programming practice to rely on this. Certainly, it makes it harder for someone to understand your code if fields are being initialized invisibly.
See difference between field variables and local variables.

Explicit call to super class constructor in java

Normally, you don't explicitly write the constructor for your parent class, but there are two cases where this is necessary:

 

Passing parameters

You want to call a parent constructor which has parameters (the default construct has no parameters). For example, if you are defining a subclass of JFrame you might do the following.

class Chairman extends Employee {
. . .
//======== constructor
public Chairman(String name_,String designation_) {
super(name_);
This was shown here.

No parameterless constructor in parent


There is no parent constructor with no parameters. Sometimes is doesn't make sense to create an object without supplying parameters.

Calling base class constructor using super in java

In java, we use super to call a constructor in a parent class. Calling the constructor for the superclass must be the first statement in the body of a constructor. If you are satisfied with the default constructor in the superclass, there is no need to make a call to it because it will be supplied automatically.

Usage

super(parameter-list);

Example

//X is super class, with attributes width, height, depth and has constructor for 3 attributes.

class Y extends X {
double weight; // weight of box // initialize width, height, and depth using super()

Y(double w, double h, double d, double m) {
super(w, h, d); // call superclass constructor
weight = m;
}
}

Calling another constructor in same class using this() in java

Often a constructor with few parameters will call a constructor with more parameters, giving default values for the missing parameters. Use this to call other constructors in the same class.

Eg.

public class Employee{
String name;
String designation;
public Employee(String name_){
name=name_;
}
public Employee(String name_,String designation_){
//here we are calling constructor with one parameter
//Suppose if we have lots of parameters, this does same some line of code
//and also gives clarity
this(name_);
designation = designation_;
}
}


This is also called local chaining of constructors. If we have lots of parameters, this helps us in making code clearer, also saving some effort of typing the line of codes, as we saw above.

Differences between methods and constructors.

  • There is no return type given in a constructor signature (header). The value is this object itself so there is no need to indicate a return value.
  • There is no return statement in the body of the constructor.
  • The first line of a constructor must either be a call on another constructor in the same class (using this), or a call on the superclass constructor (using super). If the first line is neither of these, the compiler automatically inserts a call to the parameterless super class constructor.
These differences in syntax between a constructor and method are sometimes hard to see when looking at the source. It would have been better to have had a keyword to clearly mark constructors as some languages do.

Sunday, May 1, 2011

Abstract Classes Have Constructors in decompiled code

1) In Java , we have default constructors provided for classes by the compiler (in case one is not declared).

2) The abstract classes can't be instantiated by using the new operator because they don't provide full implementation of all the methods.

Then does it make sense to have constructors inside abstract classes. Let us find it using a sample abstract class:
public abstract class Test{
   public abstract void doSomething();
}

The decompiled code for this class will show the truth about constructors in abstract classes in Java
public abstract class Test
{
    public Test()
    {
    }
    public abstract void doSomething();
}


Why?

The reason is that when a class extends any other class and an instance of the subclass is created then the constructor calls are chained and the super class constructors are invoked. This rule is no exception for abstract class

Moreover, having constructors in a class doesn't necessarily mean that instance of that class will be created using the new operator, but the constructors are intended for writing any initializing code.

Saturday, April 23, 2011

Multilevel inheritance - Calling order of constructors

In case of multilevel of inheritance , Base class constructor is called 1st.

// Demonstrate when constructors are called.
// Create a super class.
class A {
    A() {
        System.out.println("Inside A's constructor.");
    }
}

// Create a subclass by extending class A.
class B extends A {

    B() {
        System.out.println("Inside B's constructor.");
    }

}

// Create another subclass by extending B.
class C extends B {
    C() {
        System.out.println("Inside C's constructor.");
    }
}

class CallingCons {

    public static void main(String args[]) {
        C c = new C();
    }

}

The output from this program is shown here:

Inside A’s constructor

Inside B’s constructor

Inside C’s constructor


Monday, December 21, 2009

Constructor in java

When you create a new instance (a new object) of a class using the new keyword, a constructor for that class is called. Constructors are used to initialize the instance variables (fields) of an object. Constructors are similar to methods, but with some important differences.

Chitika