Monday 31 October 2011

Sun Certified Java Programmer (SCJP)

Constructors


A constructor is used when creating an object from a class. The constructor name must match the name of the class and must not have a return type. They can be overloaded, but they are not inherited by subclasses.

Invoking constructors


A constructor can be invoked only from other constructors. To invoke a constructor in the same class, invoke the this() function with matching arguments. To invoke a constructor in the superclass, invoke the super() function with matching arguments. When a subclass object is created, all the superclass constructors are invoked in the order starting from the top of the hierarchy.

Default constructors


The compiler creates the default constructor if you have not provided any other constructor in the class. It does not take any arguments. The default constructor calls the no-argument constructor of the superclass. It has the same access modifier as the class.

However, the compiler will not provide the default constructor if you have written at least one constructor in the class. For example, the following class has a constructor with two arguments defined in it. Here the compiler will give an error if we try to instantiate the class without passing any arguments because the default constructor is not available:

class Dot
{

int x, y;
Dot(int x, int y)
{


this.x = x;
this.y = y;


}


}

If you invoke the default constructor of your class and the superclass does not have a constructor without any arguments, your code will not compile. The reason is that the subclass default constructor makes an implicit call to the no-argument constructor of its superclass. For instance:

class Dot
{

int x, y;
Dot(int x, int y)
{


this.x = x;
this.y = y;


}


}

class MyDot extends Dot { }
class Test
{

public static void main(String args[])
{


MyDot dot=new MyDot();


}


}

Note: In this section, we covered the important concepts that are included in the first objective. We discussed the valid ways to declare and construct single and multi-dimensional arrays. When you understand the effect of modifiers in methods and classes, make sure you know the legal combinations of modifiers. For example, you cannot declare a final method as abstract. We also learned about constructors. Remember that the compiler provides the default no-argument constructor only when you don't write any constructors.

3 comments: