Pages

constructors programms

constructors  Notes:

Programms:

/* the following programs illustrate the concept of constructors */
Eg : 1)
/* Program to demonstrate default constructor */
class ConstructorDemo1
{
 int l;
 public static void main(String args[])
 {
 ConstructorDemo1 c1 =new ConstructorDemo1 ();
  System.out.println("Area of Square = " +     c1.l*c1.l);
 }
}// end of class ConstructorDemo1
Eg: 2)
/* Program to demonstrate constructor without parameters */
class Square
{
  int l;
  Square() // constructor
  {
    System.out.println(“Inside constructor without parameters “);
    l = 100;
  }
  void area()
  {
    System.out.println(“Area of Square = “ + l * l);
  }
 }// End of class Square
class ConstructorDemo2
{
  public static void main(String args[])
  {
    Square s = new Square(); // calls constructor method
    s.area();
  } // end of main
} // end of class ConstructorDemo2

Eg : 3)
/* Program to demonstrate constructor with parameters */
class Square
{
  int l;
  Square(int x) // constructor
  {
    System.out.println(“Inside constructor with parameters “);
    l = x;
  }
  void area()
  {
    System.out.println(“Area of Square = “ + l * l);
  }
 }// End of class Square
class ConstructorDemo3
{
  public static void main(String args[])
  {
    Square s = new Square(100); // calls constructor method
    s.area();
  } // end of main
} // end of class ConstructorDemo3

Eg : 4)
/* Program to demonstrate multiple constructors */
class Rectangle
{
  int l,b;
  Rectangle() //
  {
    System.out.println(“Inside constructor without parameters “);
    l = 100;
    b = 200;
  }
  Rectangle(int x) //
  {
    System.out.println(“Inside constructor with one parameter “);
    l = x;
    b = x;
  }
  Rectangle(int x,int y)
  {
    System.out.println(“Inside constructor with two parameters “);
    l = x;
    b = y;
  }
  void area()
  {
    System.out.println(“Area of Square = “ + l * l);
  }
 }// End of class Rectangle
class ConstructorDemo4
{
  public static void main(String args[])
  {
    Rectangle r1 = new Rectangle();
    Rectangle r2 = new Rectangle(15);
    Rectangle r3 = new Rectangle(50,150);
    r1.area();
    r2.area();
    r3.area();
  } // end of main

} // end of class ConstructorDemo4