Constructor in Java

Constructor:

       Constructor is a special type of method in Java. Constructor is used to initialize the object.

Constructor Rules:

  1. The Class and method should be same.
  2. The Constructor must have no explicit return type.

Two Type of Constructor

java constructor

Default Constructor

   The default constructor not having any parameter.

Example:

class cool
 {
    cool()
      {
           System.out.println("This is a example of default constructor");
       }
 public static void main(String args[])
   {
      cool c=new cool();
    }
  }

Output:
This is a example of default constructor

Note: If the programmer doesn't mention the constructor in the program, the compiler will automatically generate the constructor.

Why compiler automatically generate the constructor ??
         Because specifying the 0, null depends the data types.

Parametrized Constructor

    The parametrized constructor having the parameters.

Example

class chill
 {
    chill(int a, String s)
      {
           value=a;
           name=s;
        }
      void display()
        {
           System.out.println(+value+""+name);
         }
 public static void main(String args[])
   {
      chill c=new chill(333, "student");
      chill c2=new chill(444, "student2");
      c.display();
      c2.display();
    }
 }

Output:
333 student
444 studetnt2

Copy Constructor:

Example:

class chill
 {
    chill(int a, String s)
      {
           value=a;
           name=s;
       }
      chill(chill c)
        {
            value=c.value;
            name=c.name;
         }
      display()
        {
           System.out.println(+value+""+name);
         }
 public static void main(String args[])
   {
      chill c=new chill(333, "student");
      chill c2=new chill(c);
      c.display();
      c2.display();
    }
 }

Output:
333 sathish
333 sathish

Copying values with out Constructor

    class Second{ 
        int id; 
        String name; 
        Second(int i,String n){ 
        id = i; 
        name = n; 
        } 
        Second(){} 
        void display(){System.out.println(id+" "+name);} 
      
        public static void main(String args[]){ 
        Second s1 = new Second(111,"Second"); 
        Second s2 = new Second(); 
        s2.id=s1.id; 
        s2.name=s1.name; 
        s1.display(); 
        s2.display(); 
       } 
    }

Output:
111 Second
111 Second

Does constructor return any value?
   
      :yes, that is current class instance (You cannot use return type yet it returns a value).

No comments:

Post a Comment