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<>(); } }
A java blog with a collection of examples and tutorials on Java and related technologies. (Under maintenance with continuous updates) Be in touch with java jazzle or k2java.blogspot.com.
Monday, June 27, 2011
JDK7 : Improved type inference for generic instance creation(diamond)
Sunday, June 12, 2011
Insufficient memory problem with StringBuffer
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
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:
- Free up the memory (c++ suffer from memory allocation / deallocation)
- 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.
Order of initialization in java
- All data fields are initialized to their default value (0, false, or null).
- All field initializers and initialization blocks are executed, in the order in which they occur in the class declaration.
- If the first line of the constructor calls a second constructor, then the body of the second constructor is executed.
- The body of the constructor is executed.
Initialization Blocks in java
- By setting a value in a constructor
- By assigning a value in the declaration
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++;
}
}
Parameter names in constructor in java
public Employee(String n, double s)
{
name = n;
salary = s;
}
public Employee(String aName, double aSalary)
{
name = aName;
salary = aSalary;
}
public Employee(String name, double salary)
{
this.name = name;
this.salary = salary;
}
C++ convention
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
class Employee
{
. . .
private String name = "";
}
class Employee
{
. . .
static int assignId()
{
int r = nextId;
nextId++;
return r;
}
. . .
private int id = assignId();
}
Default Field Initialization in java
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 {This was shown here.
. . .
//======== constructor
public Chairman(String name_,String designation_) {
super(name_);
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 (usingsuper
). If the first line is neither of these, the compiler automatically inserts a call to the parameterless super class constructor.
Sunday, May 1, 2011
Abstract Classes Have Constructors in decompiled code
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
// 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
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. - Constructor name is class name. A constructors must have the same name as the class its in.
- Default constructor. If you don't define a constructor for a class, a default parameterless constructor is automatically created by the compiler. The default constructor calls the default parent constructor (super()) and initializes all instance variables to default value (zero for numeric types, null for object references, and false for booleans).
- Default constructor is created only if there are no constructors. If you define any constructor for your class, no default constructor is automatically created.
- Differences between methods and constructors.
-
this(...) - Calls another constructor in same class.
Use super to call a constructor in a parent class.
- Need for explicit call to base class constructor using super in java
- Default field initialization in java
- Explicit or direct field initialization in java. Also see cpp vs java on direct field initialization here.
- Naming convention in java for constructors
- Initialization block in java
- Order of initialization in java
- Static initialization in java
- Object destruction and finalize method in java