Saturday, 9 March 2013

Constructors in Java

Understanding constructors

    Constructor is a special function in the class with same function name as that of the class and no return type.It is called only once when the object is created.Note constructors have no return type but they can have access modifiers.Lets take an example to understand this better -
Lets take the same sample code previously explained and add constructor to it

package greetings;

public class MyGreetings {
   
    private String welcomeMessage;
   
    public MyGreetings()    //This is a constructor
    {
        this.welcomeMessage = "default Message";
    }

    public String getWelcomeMessage() {
        return welcomeMessage;
    }

    public void setWelcomeMessage(String welcomeMessage) {
        this.welcomeMessage = welcomeMessage;
    }
   
    public static void main(String args[])
    {
        MyGreetings greetings = new MyGreetings();
         System.out.println(greetings.getWelcomeMessage());
    }

}

In above code constructor sets default value of welcomeMessage variable to "default Message". So above code will print default Message to standard output.

Constructors can be public, private or default.

Note : If you don't write a constructor compiler writes one for you.This compiler written constructor does not have any arguments or code in it.Remember this will happen only if you have not written any constructor.

What is the use of constructors?

     constructors are use to set default values to member variables.It can also be used to initialize some instance variables when the object is created.

Can we have more than one constructor for a single class?

     Yes you can have multiple constructors in a single class but all of them must have different set of arguments. Number and type of arguments provided while creating object will decide  which constructor must be invoked.Also you can call one constructor from another using this(arguments). I understand just this description makes little sense so lets take up a fresh example to demonstrate what i just described.

public class Student
{
   private String name;
   private int age;
   public Student()  //constructor with no arguments
   {        
      this("defaultName",18);    
   } 
   public Student(String name,int age)
   { 
      this.name = name;
      this.age = age;
   }
   //getters and setters for name and age


   public String printStudentDetails()
   { 
      return("Name is" +  this.name + " and age is " + this.age  + "\n");
   } 

   public static void main(String args[])
   {
      Student student1 = new Student();
      System.out.println("student1 details are  + "student1.printStudentDetails());            
      Student student2 = new Student("John",21);
      System.out.println("student2 details are  + "student2.printStudentDetails()); 
    }  


} 




Output - 
 student1 details are Name is defaultName  and age is 18
 student2 details are Name is John and age is 21

Analysis-
When student1 is created no arguments are provided and hence default constructor is called i.e
public Student() is called which in turn calls the constructor public Student(String name,int age) with some default values.When student2 is created two arguments are passes of type string and int so constructor
public Student(String name,int age) will automatically be picked up and set name and age to values supplied as arguments.

Note : If you define constructor as private you cannot create object of that class.Reason being private functions can only be called in same class.

So why would any one declare constructor to be private?

     There are cases in which we don't want to explicitly create any objects of a class.Singleton design pattern is one of the use case.We will discuss what design patterns are ans what a singleton class means and what are it's uses but for now keep in mind such cases are very much possible.

 Summary


  • constructors have same name as that of the class.
  • constructors don't have return type.
  • A single class can have multiple constructors having different arguments.
  • We can call one constructor from another using this() keyword.
  • constructor cannot be static(will be explained later).
  • constructors don't have any return type and yet they return instance of that class.
  • You can't create object of a class whose constructor is private.
  • Which constructor must be invoked will depend on arguments passed.
  • when a constructor is invoked it executes constructor of it's super class first(will be explained in inheritance)
  • If you do not provide any constructor compiler will write one for you.This is a default constructor with no arguments.

Common mistakes

  • Constructor does not have return type. If you provide one it will not be constructor but a normal instance method.
  • See the following code -

    public class HelloWorld {
         int x;
         int y;
         public HelloWorld(int x, int y) {
            x = x;
            y = y;
        }
    }
    


    Above code is of no use. 'x' and 'y' variables that you see inside constructor are the ones coming from parameter 'x' and 'y'. They do not represent 'x' and 'y' instance variables. To initialize instance variables you need to use this  keyword.

    public class HelloWorld {
        
        int x;
        int y;
        public HelloWorld(int x, int y) {
            this.x = x;
            this.y = y;
        }
    }
    



No comments:

Post a Comment

t> UA-39527780-1 back to top