KnowledgeBoat Logo

Computer Applications

Consider the following Java class and answer the questions given below:

class Rectangle
{
  int length, breadth;

  Rectangle()
  {
    length = 5;
    breadth = 3;
  }

  Rectangle(int l, int b)
  {
    length = l;
    breadth = b;
  }

  void area()
  {
    System.out.println("Area: " + (length * breadth));
  }

  public static void main(String args[])
  {
    Rectangle r1 = new Rectangle();
    Rectangle r2 = new Rectangle(8, 4);
    r1.area();
    r2.area();
  }
}

(a) Name the type of constructors used in the above class.

(b) What is the output of the method main()?

Java Constructors

2 Likes

Answer

(a) Default constructor & Parameterized constructor
(b) Output
Area: 15
Area: 32

Reason

The types of constructors used in the given program are:

1. Default Constructor:

Rectangle()
{
  length = 5;
  breadth = 3;
}
  • A default constructor is a constructor that does not take any parameters.
  • It initializes length = 5 and breadth = 3.

2. Parameterized Constructor:

Rectangle(int l, int b)
{
  length = l;
  breadth = b;
}
  • A parameterized constructor is a constructor that takes arguments (int l and int b in this case).
  • It allows for initializing the instance variables length and breadth with specific values provided during object creation.

Output of the program

  1. Rectangle r1 = new Rectangle();
    Calls the default constructor Rectangle()length = 5 and breadth = 3

  2. Rectangle r2 = new Rectangle(8, 4);
    Calls the parameterized constructor Rectangle(int l, int b)length = 8 and breadth = 4

  3. r1.area();
    Prints value of Area → 5 x 3 = 15

  4. r2.area();
    Prints value of Area → 8 x 4 = 32

Answered By

2 Likes


Related Questions