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

Recommended Answers

All 5 Replies

Yes.

commented: Couldn't have said it better myself. :) +6

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.

commented: Great Info ... I have used it dozens of times never aware of this danger !!! +2

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;
  }
}

Thank you for all your help.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.