Sunday , October 21 2018
Home / Java Programming / What is a constructor? How It is different from other methods?

What is a constructor? How It is different from other methods?

What is a constructor? How It is different from other methods?

What is a constructor:

A constructor is a special method defined in a class implicitly or explicitly.  Its purpose is to initialize the instance variables of a class.

How It is different from other methods?

Differences between Constructor and other class methods:

A constructor is different from the other class methods in three ways.

  1. A constructor is always a public method, while other might be public, private or protected.
  2. A constructor returns nothing even it does not use ‘void’ keyword in its definition. While others might have return something.
  3. Constructor has the same name as that of the class

Example:

Consider a class student:

public class Student
{
   // instance variables
   private int rollNo ; 
   private String stdName ; 

   // a constrcutor
   public Student(int aRollNo, String aName)
   {
      rollNo = aRollNo ;
      stdName = aName ;
   }

   // rest-of-the-class-members

} // End-class-Student

How a constructor is called:

Consider a demo class / test class StudentDemo

 

public class StudentDemo
{
  public static void main(String[] args)
   {
      // creating an object std of above class Student
      // it will create a new student with rollno = 2501 and 
      // stName = "Muhammad Rizwan"
      Student std = new Student(2501, "Muhammad Rizwan") ;
     
      // rest of the logic
   }
} //end-class-studentdemo

Check Also

How to parse string in java?

How to parse string in java? Usually in natural language processing, a text is parsed. …