Monday 3 December 2012

Default and Parameterize constructor in a class?

Leave a Comment
There is only one default constructor, which is only defined when you declare no constructors for a class. Otherwise, the declared constructors will be the only constructors. If you do not include a constructor, the compiler inserts code equivalent to


public ClassName() {
  super();
}

In addition, if you do declare constructors for a class, and you don't explicitly define the constructor call of the super class, the compiler will insert a parameter matching call to the super class.



public ClassName extends SuperClassName {
 public ClassName(String item, List stuff) {
    // no explicit super class constructor called
    ...
  }

}
 
 We can use more than one parametrize constructor in java by changing its no of parameter, and 
data type of parameters, this is called constructor overloading.
 
 public class Simple {

    public Simple() {
        this(null);
    }

    public Simple(Resource r) {
        this(r, null);
    }

    public Simple(Resource r1, Resource r2) {
        

        if (r1 == null) {
            r1 = new Resource();
        }
        if (r2 == null) {
            r2 = new Resource();
        }

 
    }

}

0 comments:

Post a Comment