Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Call a method from a constructor  RSS feed

 
Sara Tracy
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi !
Can I make a method call from a constructor as given below :




thanks
-Sara
 
Campbell Ritchie
Marshal
Posts: 55672
161
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes.
Constructors are there to set up the initial state of your object. So you can in theory call any method from a constructor method, but you really ought only to call methods which set up your object's initial state.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yup, that should be fine.

Do note that "this" is not assured to be good for anything until the constructor is done. Be careful not to pass "this" from the constructor to anything that needs a complete ready-to-use object.
 
Sara Tracy
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Campbell and Stan !
 
Campbell Ritchie
Marshal
Posts: 55672
161
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's a pleasure
 
megha ghanekar
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Sara,
U can certainly do that. But take care of following situation.

class Base
{

Base()
{
disp();
}
public void disp()
{
System.out.println("in disp of Base");
}

}

class Derived extends Base
{

Derived()
{

}
public void disp()
{
System.out.println("in disp of Derived");
}

}

class OverrideDemo
{
public static void main(String[] args)
{

Base b1 = new Base(); // case 1 : Base class disp called
Base b2 = new Derived(); // case 2: Derived class disp called

}
};

If there is a call to a method from constructor in Base class & if u create an object of type Base, it works fine as in case 1. But if you derive a class from such a base class & you override that method in the derived class. The derived class method will be called from Base class constructor.


Warm Regards,
meghana
 
Richard Green
Ranch Hand
Posts: 536
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

private String getPwd(String car_type) throws Exception


This is just bad practise. Do something like


private String getPwd(String car_type) throws PasswordNotFoundException


instead.

where PasswordNotFoundException extends the Exception class.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!