Hi
can u call an Instance method from the constructor in java. thanks for your help.

absolutely.

i do that most of the time.

an example lets say i have created a class Me.java which has the following constructors

public Me()
{}
public Me(String s)
{}
public Me(int dead)
{}

public static void main(String[] args)
{
Me theBasicConstructor = new Me();
Me theStringConstructor = new Me("Hello");
Me theIntegerConstructor = new Me(23);
}

i hope that this will give you the idea

Yes.

I feel I need to qualify this remark.

That method should be final, because if someone extends your class, you will probably wind up with unexpected (and quite probably, for your class, catastrophic) effects if the method called from the constructor is overridden, as the overridden method would be called, rather than the original.

Comments
Great Info ... I have used it dozens of times never aware of this danger !!!

absolutely.

i do that most of the time.

an example lets say i have created a class Me.java which has the following constructors

public Me()
{}
public Me(String s)
{}
public Me(int dead)
{}

public static void main(String[] args)
{
Me theBasicConstructor = new Me();
Me theStringConstructor = new Me("Hello");
Me theIntegerConstructor = new Me(23);
}

i hope that this will give you the idea

The question was - can you call an instance method from a constructor? Your example calls constructors from the main method which is different. This is a simple example of what codered152 was asking for:

public class Me
{

  private String name;

  public Me(String aName)
  {
    setName(aName);
  }

  public void setName(String aName)
  {
    name = aName;
  }
}
This article has been dead for over six months. Start a new discussion instead.