DotNetBlocks

Things on DotNet, programming, and other useless stuff

What are Constructors, and how are Constructors used?

Constructors are methods or subroutines that are called when a new instance of a class is created as an object. The constructor is called to initialize the values of the internal variables (data members) in the object and other advanced data types that form a Has-A relationship with the object. The constructor also has no return type.

Like all methods and functions in object oriented programming, the constructor can be overloaded to allow for initializing the class based on the data the creator of the object has at the time of the objects creation.

Example of an overloaded constructor:

//----------------------------------------------------------
public class Person {
     // instance variables:
     String name;
     String phoneNumber;
 
     // Constructor with name and number:
     public Person(String name, String phoneNumber){
         this.name=name;
         this.phoneNumber=phoneNumber;
     }
 
     // Alternative constructor without giving phone number.
     // This will set the phone number to "N/A" (for "not available")
     public Person(String name){
         this(name, "N/A");
     }
 }
//----------------------------------------------------------

Code Example From: http://en.wikipedia.org/wiki/Method_overloading

The class Person has two constructors called Person, both can take the variable name but only the first method can take the phone number. To overload a method, you must create two or more methods with the same name but with different method signatures.  The method signature is based on the types of parameters passed into the function, and the order in which they appear in the method’s definition.

Example of 2 unique signatures:

//----------------------------------------------------------
     public Person(String name, String phoneNumber)
     public Person(String name)
//----------------------------------------------------------

Comments are closed