Constructors in Java

Constructors in Java.

-- A constructor is a special method of function  that is used to   initialize an object in java.
--  every class has a constructor by default.

--  compiler build a default constructor for that class.
--  constructor are executed at time of object creation of class. 
--  there are no return type in java constructor
--  An interface cannot have the constructor in java.
--  Constructors cannot be private modifire.
--  Constructors name must be similar to that of the class name.

 There are 2 type of constructor in Java : 

 1) Default Constructor.

 2) Parameterized constructor.

 

 1) Default Constructor.

--  A java constructor that has no parameter is known as default constructor. thats build by compiler.

--  if we write a constructor with parameter or non-parameter then compiler does not create default constructor.

example of default constructor :

class JavaConstructor {

       JavaConstructor(){
         
          System.out.println("java constructor is here"):   

       }

       public static void main ( String args [] ) { 

         JavaConstructor object = new JavaConstructor( ); 
    
         // default constructor
      
     }
}

 1) Parameterized Constructor.

--  A java constructor that has parameter is known as parameterized constructor.

example of parameterized constructor :

class JavaConstructor {

       JavaConstructor( String name , int age ){
         
          System.out.println("java parameterized constructor is here "); 

          System.out.println("name is : "+name+ "age is : "+ age);

       }

       public static void main ( String args [] ) { 

         JavaConstructor object = new JavaConstructor ("nirav patel", 24 );
      
     }
}


Constructor Overloading in JAVA: 

     we can overload constructors for creating objects in different ways.like methods or functions. Compiler differentiates constructors on the basis of numbers of parameters, types of the parameters and order of the parameters. here is example of it
example of constructor overloading :

class JavaConstructor {

        JavaConstructor( String city) {
         
            System.out.println("city is : " + city);    

        }

        JavaConstructor( String name , int age ) {
         
          System.out.println("java parameterized constructor is here ");   

          System.out.println("name is : "+name+ "age is : "+ age);

        }

       public static void main ( String args [] ) { 

         JavaConstructor object = new JavaConstructor("nirav patel", 24 );

         JavaConstructor object = new JavaConstructor(" Ahemdabad ");  
      
     }

}

  


 thank you ..happy learning 😅

  


Comments

Popular posts from this blog

Java LinkedList class in Collection

Java ArrayList class in collections