Tuesday, 3 November 2015

What is Constructors,Constructor Overloading and Copy-Constructor?



Constructors: The main purpose of having constructors is to create an instance of a class.They are invoked while creating an instance of a class.

The silent features of Java constructors:

  • Constructors can be public, private or protected.
  • If a constructor with arguments has been defined in a class, you can no longer use a default no-argument constructor. you have to write one.
  • They are called only once when the class is being instantiated.
  • They must have the same name as class itself.
  • They do not return a value and you don not have to specify the keyword void.
  • If you do not create a constructor for the class, Java helps you by using a so called default no-argument constructor.

 public class SampleProgram {  
      String name;  
      // This is the the constructor  
      public SampleProgram(String name) {  
           this.name = name;  
      }  
      public void display() {  
           System.out.println("Name is :" + name);  
      }  
      /**  
       * @param args  
       */  
      public static void main(String[] args) {  
           SampleProgram s = new SampleProgram("Ashish");  
           s.display();  
      }  
 }  


Constructor Overloading:- In constructor overloading ,we pass different number and type of variable as arguments all of which are private variables of the class.

 public class SampleProgram {  
      String name;  
      public SampleProgram() {  
           this.name = "Manish";  
      }  
      // This is the the constructor  
      SampleProgram(String name) {  
           this.name = name;  
      }  
      public void display() {  
           System.out.println("Name is :" + name);  
      }  
      /**  
       * @param args  
       */  
      public static void main(String[] args) {  
           SampleProgram s = new SampleProgram("Ashish");  
           s.display();  
           SampleProgram s1=new SampleProgram();  
           s1.display();  
      }  
 }  


Copy Constructor:- A copy constructor is a type of constructor which constructs the object of the class from another object of the same class.The copy constructor accepts a refernce to tis own class as parameter.

Note:- Java does not support Copy Constructor.So don't get confused.It is supported in C++.


Enjoy Reading:)




No comments:

Post a Comment