Java Oops Ch2 Constructors

Constructors

Definition:

A constructor initializes an object immediately upon creation.

Important points:

Types of constructors: Default(No arguments) and Parameterized.

Default Constructors:

Constructors with no arguments.

Example:

class Rectangle
{
   double width;
   double height;
  Rectangle()
  {
    width=10;
    height=20;
  }
  double perimeter()
  {
    double p= 2*(width+height);
    return p;
  }
 }
 class Main
 {
 public static void main(String args[])
 {
   Rectangle rec1=new Rectangle();
   
   double vol;
   
    vol=rec1.width * rec1.height; 
   System.out.println("Rectangle 1 area:  "+vol);
   System.out.println("Rectangle 1 perimeter method:  "+rec1.perimeter());
  
  
      }
 }
 

### Result: Rectangle 1 area: 200.0
Rectangle 1 perimeter method: 60.0 ## Parameterized Constructors

 class Rectangle
{
   double width;
   double height;
  Rectangle(double w, double h)
  {
    width=w;
    height=h;
  }
  double perimeter()
  {
    double p= 2*(width+height);
    return p;
  }
 }
 class Main
 {
 public static void main(String args[])
 {
   Rectangle rec1=new Rectangle(10,20);
   
   double vol;
   
    vol=rec1.width * rec1.height; 
   System.out.println("Rectangle 1 area:  "+vol);
   System.out.println("Rectangle 1 perimeter method:  "+rec1.perimeter());
  
  
      }
 }
 

### Result Rectangle 1 area: 200.0
Rectangle 1 perimeter method: 60.0