Computer Science, asked by Afridicse, 1 year ago

Why do we need constructor as a class member in java?

Answers

Answered by Rajdeep11111
25
HEYY FRIEND!

A Constructor is a member method with the same name as the class name.

We need a constructor as a class member in Java to initialize the instance variables which are declared.

This initialization can be done in two ways:

=> Direct initialization using a Default Constructor, in which direct values are assigned to the variables without passing parameters.

=> Through parameters using a Parameterized Constructor, in which arguments (values) are assigned to the instance variables through parameters as defined in the header (or Constructor prototype).



For example,
Consider the following program snippet:

class Sample
{
int a, b;
Sample()      //Default Constructor
{
a = 0;
b = 1;
}
Sample(int x, int y)    //Parameterized Constructor
{
a = x;
b = y;
}
public static void main (String args[])
{
Sample ob1 = new Sample();    //The default constructor gets invoked
Sample ob2 = new Sample(2, 5);   //The parameterized constructor gets invoked.
}
}


THANKS!

Answered by shaikhafsa
6
constructor is used on only for initialisation purpose the two types of constructors are
default and parameterised constructor

hope it helps plz mark as bbrainliest

Rajdeep11111: :-)
shaikhafsa: plz
Similar questions