6 Years
Discussion Span
Last Post by Xufyan

Its a special method that is called when a new instance of a class is created. It's used to initialise anything that needs to be initialised for a new instance. Every class needs at least one, and if you don't supply one the compiler gives you a "default" constructor that does nothing. You can define constructors with different parameters, depending on how you want to initialise your new instance.

Votes + Comments
very useful info

thanks for that help. can you give me an example through a small program?i will understand it better with an example..waiting for your reply!


Just have a look at any of the recent posts here - you'll find a constructor in most of the pieces of code. You can identify one because its name is the same as the name of the class, eg

class X{
   public x() { // this is a constructor
     // do some stuff

take this example,

class Employee{
  int num;
  public Employee(){ // this is constructor 
    num = 99; // the default values for num is set to 99

This is not a main class , later in a program if you used this class in main class and didn't define any value for num the default value would be called from the constructor and the value will be automatically set to 99.
See this,

class Emp{
public static void main (String args[]){
Employee first = new Employee();
Employee second = new Employee();
first.num = 100;

Since no value for the num is defined for second , it will automatically set to 99 !

Edited by Xufyan: n/a

Votes + Comments
very nice
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.