Constructors and Destructors

Constructor:

  1. always public,no return type, same name as class
  2. used for the purpose of initialization
  3. when an object is created first of all constructor runs
  4. all variables should be initialized in this in order to prevent the compiler from taking garbage values
  5. Can be parameterized or unparameterized

Destructor: used for reallocating memory. not widely used in java. {finalize();}

import java.util.Scanner;

class Rectangle
{
int x, y;
int width, height;

Rectangle() {
this(0, 0, 0, 0);
System.out.println(” You are in the first constructor:”);
System.out.println(” x:” + ” ” + x);
System.out.println(” y:” + ” ” + y);
System.out.println(” width:” + ” ” + width );
System.out.println(” height:” + ” ” + height);
}
Rectangle(int width, int height) {
this(0, 0, width, height);
System.out.println(” You are in the second constructor:”);
System.out.println(” x:” + ” ” + x);
System.out.println(” y:” + ” ” + y);
System.out.println(” width:” + ” ” + width );
System.out.println(” height:” + ” ” + height);

}
Rectangle(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
System.out.println(” You are in the third constructor:”);
System.out.println(” x:” + ” ” + x);
System.out.println(” y:” + ” ” + y);
System.out.println(” width:” + ” ” + width );
System.out.println(” height:” + ” ” + height);

}

}

class rr
{
public static void main(String s[])
{
System.out.println(“Value 1:”);
Scanner ss= new Scanner(System.in);
int o=ss.nextInt();
System.out.println(“Value 2:”);
int t= ss.nextInt();
Rectangle rect= new Rectangle(o,t);

}
}

Advertisements

Constructive and genuine appreciation and/or criticism most welcome

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s