Constructor and need of constructor with example in java

Constructor: constructor is a special method of a class or structure in object-oriented programming that initializes an object of that type. A constructor is an instance method that usually has the same name as the class, and can be used to set the values of the members of an object, either to default or to user-defined values .Constructor can not return any type of values as shown in given example.

Example:

import java.lang.*;
import java.io.*;
import java.util.*;

Class ConstructorDemo

{
public ConstructorDemo()
{
int num,i,j,value,sum=0; 
Scanner s= new Scanner(System.in);
System.out.println("Enter number howmany number do you want addition.");
num=s.nextInt();
System.out.println("Enter numbers :");
for(i=1; i<=num; i++)
{
value=s.nextInt();
sum=sum+value;
}
System.out.println("Result :"+sum);
}
public ConstructorDemo(int num)
{
    Scanner s=new Scanner(System.in);
int i,j,value,mul=1;
System.out.println("Enter numbers :");
for(i=1; i<=num; i++)
{
value=s.nextInt();
mul=mul*value;
}
System.out.println("Result :"+mul);

}

}

Class Tcd
{
public static void main(String args[])
{
    int num;
Scanner c=new Scanner(System.in);
ConstructorDemo obj1=new ConstructorDemo();
System.out.println("Enter number howmany number do you want multipication.");
num=c.nextInt();
ConstructorDemo obj2=new ConstructorDemo(num);
}


}

The need  of constructor is to initialize the object of a class while the need of a method is to perform a task by executing java code. Constructors cannot be abstract, final, static and synchronised while methods can be. Constructors do not have return types while methods do.







Expected output is :









Post a Comment

0 Comments