Parameterized constructors

The constructor we learned about in the previous section is the default constructor because it does not accept any values. In a parametric constructor with the same syntax, we actually come up with some parameters, as shown in the following screenshot:

Output for the parameterized constructor using the given code 

The only difference between the previous constructor and this one is that here we are passing the parameters, and in the default one pass it without any parameters. When we run our code, whenever we create an object, if we don't pass any parameters, the compiler automatically picks the default constructor, as shown in the following screenshot:

Output when the default parameter is passed

Now, let's create one more object for the same class with parameters:

constructDemo c=new constructDemo(4,5);

When we define parameters as mentioned in the preceding syntax, the compiler checks whether there is any constructor with the two arguments of the integer type while executing the runtime. If it finds a constructor, it executes the following code syntax instead:

public constructDemo(int a, int b)
{
System.out.println("I am in the parameterized constructor");
}

In cases where a parameter is not defined, the compiler executes the default constructor. The output for the preceding code will be:

 I am in the parameterized constructor

At runtime, when creating an object, we have to give the parameters, so during execution, it will compare the parameters with the constructors defined. Similarly, we can create multiple objects for the same class:

constructDemo cd=new constructDemo();
constructDemo c=new constructDemo(4,5);

When both the constructors are run together, the output will be:

I am in the constructor
I am in the constructor lecture 1
I am in the parameterized constructor

Now, we will create one more constructor of a similar type, but this time with only one parameter:

public constructDemo(String str)
{
System.out.println(str);
}
public static void main(String[] args)
{
constructDemo cd=new constructDemo("hello");
}

The output will be:

hello

Thus, the Java compiler gives preference to the explicit constructor if we define something explicitly, otherwise it prints the implicit constructor. The key points to be noted here are that it  will not return any value and the constructor has to be defined with the class name only.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.58.150.59