Sunday, 31 July 2011

Constructors


CONSTRUCTORS:

When the object is created, Java performs default initialization, char variables are set to '\u0000', byte, short, int, long to zero, boolean to false, float to 0.0

All objects that are created must be given initial values. We can do it,

  1. By assigning the value to instance variable using dot operator.
  2. Through instance method for e.g get data()
  3. By using constructor method to initialize an object when it is first created.
  • Constructors have the same name as class itself.
  • Constructors do not specify a return type.
  • Constructors is called automatically by the run time system.
For e.g.

class Rectangle
{
int length,width;
Rectangle(int x, int y) //constructors
{
length = x;
width = y;
}
int rectArea()
{
return(length*width);
}
}

class ABC
{
public static void main(String args[])
{
Rectangle rect=new Rectangle();
Rectang lerect1=new Rectangle(15,10) //calling constructor
int area1=rect1.rectArea();
System.out.println(“Area1 = “+ area1);
}
}


                                                              Constructors

If you do not provide any constructors, a default no-arg constructor is provided for you. This constructor takes no arguments and does nothing. If you want a specific no argument constructor as well as constructors that take arguments, you must explicitly provide your own no argument constructor.

DEFAULT CONSTRUCTOR:
If no constructors are declared in a class, the compiler will create a default constructor that takes no parameter.
When you create a new Movie object, the compiler decides which constructor to call, based on the argument specified in parentheses in the new statement. Constructor can call another constructor of the same class by using this() syntax. By using this(), you can avoid duplicate code in multiple constructors. This technique is used when initialization routine is complex.

Public class Movie
{
private String title;
private String rating;
public Movie()
{
this(“G”);
}
public Movie (String newRating)
{
raing = newRating;
}
}
RULES: The call to this() must be the first statement in the constructor. The argument to this() must match those of the target constructor.

No comments:

Post a Comment