MY mENU


Thursday 9 February 2012

Constructors in Java

Constructors: Constructors are block of codes which gets executed when the class is instantiated. IT provides initial state to the object i.e object initialization and also for resource allocation. It has a public, Private, & protected modifiers. It is used to initialize a class through object. Important properties of constructors are,

• A constructor doesn’t have a return type.
• The name of the constructor must be the same as the name of the class.
• Unlike methods, constructors are not considered to be members of a class.
• A constructor is called when a new instance of an object is created. In fact, it’s the new keyword that calls the constructor. After creating the object, you can’t call the constructor again.


If we create only object the constructor is not called. that is

Example obj; //cant call the constructor


Here’s the syntax for coding a constructor:

public ClassName (parameter-list) [throws exception...]
{
statements...
}


If no user defined constructor is provided for a class, compiler initializes member variables to its default values.
  • numeric data types are set to 0
  • char data types are set to null character(‘\0’)
  • reference variables are set to null

Basic Constructors The most obvious work of a constructor is to initialize the fields with values. The values may come as parameter-list for constructor or as a result of certain expressions or the like. One of such example is given below.

public Triangle(float a, float b, float c){
side1 = a;
side2 = b;
side3 = c;
}

Constructors can also be overloaded. For example the above code initializes the Triangle class which consists of three fields representing three sides of a triangle. If we decide to add another constructor which accepts two sides and one angle as parameters yes, we can. The following code illustrates this.

public Triangle(float a, float b, double theta){
side1 = a;
side2 = b;
side3 = (float) Math.sqrt( (a * a) + (b * b) – 2 * a * b *
Math.cos(theta) );//cosine rule
}

Now both of the below statements can be used to instantiate the Triangle class. 
Triangle t1 = new Triangle(10, 20, 30);//arbitrary triangle
Triangle t2 = new Triangle(10, 20, 90.0);//right angled triangle

Default Constructors Every class should have at least one constructor. If we add none, Java will add one with empty body, empty parameter-list and public access modifier. Such added constructor is known as default constructor. But if we add at least one, Java will add nothing. So be clear, if you added a constructor with parameter-list then you have no way to instantiate the class without passing parameters unless or until you explicitly create a parameter less constructor.

class A { }
class B {
public B(int a){
}
}
class Demo {
public static void main(String args[]){
A a = new A(); //No error
B b = new B(); //Error
B b = new B(10); //No error
}
}

Calling Other Constructors Calling other constructors of the same class is done by using the this keyword. This technique is commonly used when you have several constructors that build on each other.

NOTE One of a good programing practice is, if more than one constructor is used then cascade them as
possible. Make sure that only a single copy of the code actually initializes and all other constructors call it. For example the example in previous page can be rewritten as,

 public Triangle(float a, float b, float c){
side1 = a;
side2 = b;
side3 = c;
}
public Triangle(float a, float b, double theta){
this(a, b, (float)Math.sqrt((a * a) + (b * b) – 2 * a * b *
Math.cos(theta) ));
}

Remember,
• this() must be the first statement in the constructor.
• You can't invoke more than one constructor from a constructor.


Create your First Constructor
Step 1: Type following code in your editor

class Demo{
int value1;
int value2;
Demo(){
value1 = 10;
value2 = 20;
System.out.println("Inside Constructor");
}
public void display(){
System.out.println("Value1 === "+value1);
System.out.println("Value2 === "+value2);
}
public static void main(String args[]){
Demo d1 = new Demo();
d1.display();
}
}
}


No comments:

Post a Comment